我刚开始接触canvas和java script,并不知道为什么它不能正常工作。这两个警告框已经弹出,但是画布的颜色并没有按照我预期每隔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');