canvas 绘制文本

 

 

 

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    body {
      text-align: center;
    }
    canvas {
      background: #ddd;
    }
  </style>
</head>
<body>
  <h3>绘制文本</h3>
  <canvas id="c11" width="500" height="400"></canvas>
  <script>
    var ctx = c11.getContext('2d');

    var txt = 'abgyj中国123';
    ctx.font = '30px SimHei';
    ctx.textBaseline = 'top';
    //ctx.fillText(txt, 0, 0);
    ctx.strokeText(txt, 0, 0);


    console.log( ctx.measureText(txt) )
  </script>
</body>
</html>

 

结果:

代码:

 

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    body {
      text-align: center;
    }
    canvas {
      background: #ddd;
    }
  </style>
</head>
<body>
  <h3>绘制文本</h3>
  <canvas id="c11" width="500" height="400"></canvas>
  <script>
    var ctx = c11.getContext('2d');

    var txt = 'dsfadf你好';
    ctx.font = '30px SimHei';
    ctx.textBaseline = 'top';

    //左上角
    ctx.strokeText(txt, 0, 0);

    //右上角
    var w = ctx.measureText(txt).width;
    ctx.strokeText(txt, 500-w, 0);

    //左下角
    ctx.fillText(txt, 0, 400-30);
    //右下角
    ctx.fillText(txt, 500-w, 400-30);
  </script>
</body>
</html>

 

 

结果:

代码:

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    body {
      text-align: center;
    }
    canvas {
      background: #ddd;
    }
  </style>
</head>
<body>
  <h3>绘制文本</h3>
  <canvas id="c11" width="500" height="400"></canvas>
  <script>
    var ctx = c11.getContext('2d');

    var txt = '明天会更好!';
    ctx.font = '60px SimHei';
    ctx.textBaseline = 'top';
    ctx.strokeStyle = '#f00';

    var w = ctx.measureText(txt).width;
    var x = -w;
    var y = 0;
    setInterval(function(){
      //清除已有内容
      ctx.clearRect(0,0, 500, 400);
      //重新绘制文本
      ctx.strokeText(txt, x, y);
      x += 10;
      if(x>=500){   //文本已到最右侧
        x = -w;
      }
    }, 50)

  </script>
</body>
</html>

 

posted @ 2017-05-26 00:27  快乐的咸鱼  阅读(369)  评论(0编辑  收藏  举报