使用Javascript在Canvas中的圆弧上绘制文本的问题

时间:2019-06-03 22:55:13

标签: javascript text html5-canvas curve

我想使用Javascript在HTML画布的弧形上绘制“用户提供的文本”。这是我见过的最贴切的例子: Create an arc text using canvas

但是在我的代码中,我不断收到“ Uncaught TypeError:无法读取null的属性'getContext'”我在哪里出错?

HTML

<!DOCTYPE HTML>
<html>
<head>
  <style>
    body {
      margin: 0px;
      padding: 0px;
    }
#canvas{
  display:block;
  margin:0 auto;
}
  </style>
<script src="textOnPath3.js"></script>
</head>
<body>
<canvas id="myCanvas" width="900" height="400" style="border:1px solid #ff0000;"></canvas>
</body>
</html>

JAVASCRIPT

 window.addEventListener("load", eventWindowLoaded, false);

      var canvas = document.getElementById('myCanvas'), 
        context = canvas.getContext('2d'),
        centerX = canvas.width / 2,
        centerY = canvas.height - 30,
        angle = Math.PI * 0.8,
        radius = 150;

      context.font = '30pt helvetica';
      context.textAlign = 'center';
      context.fillStyle = 'red';
      context.strokeStyle = 'blue';
      context.lineWidth = 4;
      drawTextAlongArc(context, 'Arc Canvas Text', centerX, centerY, radius, angle);

      // draw circle underneath text
      context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
      context.stroke();

function eventWindowLoaded () {
    drawTextAlongArc();
}
function drawTextAlongArc(context, str, centerX, centerY, radius, angle) {
        var len = str.length, s;
        context.save();
        context.translate(centerX, centerY);
        context.rotate(-1 * angle / 2);
        context.rotate(-1 * (angle / len) / 2);
        for(var n = 0; n < len; n++) {
          context.rotate(angle / len);
          context.save();
          context.translate(0, -1 * radius);
          s = str[n];
          context.fillText(s, 0, 0);
          context.restore();
        }
        context.restore();
}

1 个答案:

答案 0 :(得分:0)

问题是,尽管您已经添加了事件侦听器来检查页面是否已完成加载,但它只会调用函数 eventWindowLoaded

这意味着此行之后的所有其他命令

window.addEventListener("load", eventWindowLoaded, false);

无论是否加载,都会被调用。

所以一旦到达

context = canvas.getContext('2d')

它将因您得到的错误而失败。 html canvas元素尚不可用,因此canvas的值将不确定。

要解决此问题,请将所有内容包装在 eventWindowLoaded 函数中,例如:

 window.addEventListener("load", eventWindowLoaded, false);

 function eventWindowLoaded() {
   var canvas = document.getElementById('myCanvas');
   context = canvas.getContext('2d');
   centerX = canvas.width / 2;
   centerY = canvas.height - 30;
   angle = Math.PI * 0.8;
   radius = 150;

   context.font = '30pt helvetica';
   context.textAlign = 'center';
   context.fillStyle = 'red';
   context.strokeStyle = 'blue';
   context.lineWidth = 4;
   drawTextAlongArc(context, 'Arc Canvas Text', centerX, centerY, radius, angle);

   // draw circle underneath text
   context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
   context.stroke();

   drawTextAlongArc();
 }