.fillStyle不起作用,我的代码有问题吗?或者画布的.fillStyle的替代品?

时间:2018-06-13 20:27:41

标签: javascript html5 canvas



var canvas
var canvasContext

window.onload = function() {
  console.log("Hello World");
  canvas = document.getElementById('gameCanvas');
  canvasContext = canvas.getContext('2d');
  canvasContext.fillStyle = 'black';
  canvasContext.fillRect(0, 0 canvas.width, canvas.height);
}

<canvas id="gameCanvas" width="800" height="600"></canvas>
&#13;
&#13;
&#13;

我无法弄清楚为什么canvasContext.fillStyle不起作用。有关为什么它不起作用或替换该功能的任何建议?

3 个答案:

答案 0 :(得分:1)

似乎有效。可能是fillRect中缺少的逗号?

    var canvas
    var canvasContext

    window.onload = function(){
    console.log("Hello World");
    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');
    canvasContext.fillStyle = 'black';
    canvasContext.fillRect(0,0,canvas.width,canvas.height);
}
<canvas id ="gameCanvas" width="40"height="40"></canvas>

答案 1 :(得分:0)

似乎问题不是你的canvas / canvasContext,但你的window.onload函数不会内联,至少在stackBlitz上。你是否需要在窗口加载后明确显示它?

Stackblitz here.

答案 2 :(得分:0)

,部分遗漏了简单fillRect

var canvas
var canvasContext

window.onload = function() {
  console.log("Hello World");
  canvas = document.getElementById('gameCanvas');
  canvasContext = canvas.getContext('2d');
  canvasContext.fillStyle = 'black';
  canvasContext.fillRect(0, 0, canvas.width, canvas.height);
}
<canvas id="gameCanvas" width="800" height="600"></canvas>