canvas fillRect()不起作用

时间:2017-06-18 17:27:33

标签: javascript canvas

我是canvas和java脚本的新手,不知道它为什么不起作用。 2个警报正在发射,但画布的颜色并没有像我预期的那样每1秒发生变化。

    var canvas = function(width, height, color){
    this.width = width;
    this.height = height;
    this.color = color;
    var instance = document.createElement('canvas');
    document.body.appendChild(instance);
    instance.width = this.width;
    instance.height = this.height;
    var ctx = instance.getContext('2d');
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, this.width, this.height);

    this.changeBackground = function(color){
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, this.width, this.height);
    }

    this.clear = function(){
        ctx.clearRect(0, 0, this.width, this.height);
    }
    var flag = true;
    setInterval(function(){
        if(flag) {
            ctx.fillStyle = 'blue';
            ctx.fillRect(0, 0, this.width, this.height);
            alert('blue');
        }
        else {
            ctx.fillStyle = 'green';
            ctx.fillRect(0, 0, this.width, this.height);
            alert('green');
        }
        flag = !flag;
    },1000);
    }

    var gameCanvas = new canvas(800, 600, 'green');

3 个答案:

答案 0 :(得分:3)

问题是this setInterval内部是全局window对象,因此this.widthundefined。解决此问题的最简单方法是将传递给setInterval的函数转换为箭头函数。 Here is a fiddle

setInterval(() => {
    ...
},1000);

箭头函数继承其上下文,因此this仍然是您的画布对象。

注意:IE v11及更低版本不支持箭头功能。 Here是支持的浏览器列表。

如果您无法使用箭头功能,则可以使用ctxctx.canvas.clientWidth Here is a fiddle

ctx.canvas.clientHeight获取画布的大小

答案 1 :(得分:1)

撰写setInterval( () => {代替setInterval(function(){可以解决此问题。

胖箭头函数或lamda函数或() =>会将this指向您的类函数而不是window变量。

在回调中使用function()将始终将this指向已使用函数的实现来自的对象。
在您的情况下,setIntervalwindow全局变量

的函数

答案 2 :(得分:0)

if(flag) {
 ctx.fillStyle = 'blue';
 ctx.fillRect(0, 0, canvas.width, canvas.height);
 alert('blue');
} 
else {
 ctx.fillStyle = 'green';
 ctx.fillRect(0, 0, canvas.width, canvas.height);
 alert('green');
}
setInterval中的

this上下文为window。修复此问题可以解决您的问题。

相关问题