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

Problem with Drawing Text on an Arc in Canvas using Javascript

我想使用 Javascript 在 HTML canvas 的弧形上绘制 "user-supplied text"。这是我见过的最接近灵魂的例子: Create an arc text using canvas

但是在我的代码中,我不断收到 "Uncaught TypeError: Cannot read property 'getContext' of null" 我哪里出错了?

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();
}

问题是虽然您添加了事件侦听器来检查页面是否完成加载,但它只会调用函数 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();
 }