功能的画布部分无法运行?

时间:2018-07-11 19:58:30

标签: javascript

changeCanvasBackground = function() {
  document.getElementById("ji").innerHTML = "Paragraph changed!";
  var canvas = document.getElementById('myCanvas');
  document.getElementById("ji").innerHTML = "Paragraph changed two!";
  var ctx = canvas.getContext('2D');
  ctx.fillStyle("Red");
}
document.addEventListener('DOMContentLoaded', changeCanvasBackground);
<p id="ji">Hello</p>
<div id="gameArea">
  <canvas id="myCanvas" width="800" height="480"></canvas>
</div>

'changeCanvasBackground'函数确实运行,但是画布部分没有运行,'document.getElementById(“ ji”)'在那里显示了这一点。如果有人可以帮助我。

1 个答案:

答案 0 :(得分:2)

  • getContext接受小写字符2d
  • 您需要在fillStyle之后调用fillRect
  • fillStyle是属性而不是方法

所以三行应如下所示:

var ctx = canvas.getContext('2d');
ctx.fillStyle = "Red";
ctx.fillRect(0, 0, canvas.width, canvas.height);

最终结果将如下所示:

changeCanvasBackground = function() {
  document.getElementById("ji").innerHTML = "Paragraph changed!";
  var canvas = document.getElementById('myCanvas');
  document.getElementById("ji").innerHTML = "Paragraph changed two!";
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = "Red";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
document.addEventListener('DOMContentLoaded', changeCanvasBackground);
<p id="ji">Hello</p>
<div id="gameArea">
  <canvas id="myCanvas" width="800" height="480"></canvas>
</div>