我正在尝试使用 if 语句清除画布动画,但是当我单击清除按钮时没有任何反应,任何建议。我是否还需要删除对象以节省内存,或者一旦我清除画布它就会释放内存
<canvas id="demo" width=720 height=550></canvas>
<input type="button" id="clear" value="Clear">
.
var doChange = true;
window.onload=function(){
var demo= document.getElementById('demo');
var ctx = demo.getContext('2d');
document.getElementById('clear').addEventListener('click', function() {
doChange=false;
ctx.clearRect(0, 0, demo.width, demo.height);
console.log("clear");
}, false);
var animObjects = [];
animObjects.push(new animRectangle(ctx, 0, 90, 80,80, 'yellow', 3, 3));
loop(doChange);
function loop(doChange) {
if(doChange==true){
ctx.clearRect(0, 0, demo.width, demo.height);
for(var i = 0, ao; ao = animObjects[i]; i++) {
ao.update();
}
requestAnimationFrame(loop);
}
}
function animRectangle(ctx, x, y, XSize,YSize, color, dx, dy) {
var me = this;
this.x = x;
this.y = y;
this.XSize = XSize;
this.XSize = XSize;
this.color = color;
this.dx = dx;
this.dy = dy;
var bool = 0;
this.update = function() {
if (me.x < 0 || me.x > ctx.canvas.width-80){
me.dx = -me.dx;
}
if (me.y < 50 || me.y > 200){
me.dy = -me.dy;
}
me.x += me.dx;
me.y += me.dy;
render();
}
function render() {
ctx.beginPath();
ctx.rect(me.x, me.y, me.XSize, me.XSize);
ctx.closePath();
ctx.fillStyle = me.color;
ctx.fill();
}
return this;
}