如何清除动画以使其看起来像块正在移动。现在他们只是扩展,我不能让它工作context.clearRect(0, 0, elem.width, elem.height);
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body >
<canvas id="myCanvas" width="500" height="500" style="border:1px solid red">
<p>Your browser doesn't support canvas.</p>
</canvas>
</body>
</html>
<script type ="text/javascript">
var context;
function Shape(x, y, w, h, fill) {
this.speedX = 1;
this.speedY = 1;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
// get canvas element.
var elem = document.getElementById('myCanvas');
// check if context exist
if (elem.getContext) {
context = elem.getContext('2d');
var myRect = [];
myRect.push(new Shape(10, 0, 25, 25, "#333"))
myRect.push(new Shape(0, 40, 39, 25, "#333"))
myRect.push(new Shape(0, 80, 100, 25, "#333"))
for (i in myRect) {
//console.log(x);
context.fillRect(myRect[i].x, myRect[i].y, myRect[i].w, myRect[i].h)
//context.fillStyle = i.fill;
}
////// x, y, width, height
//context.fillRect(0, 0, 50, 50);
//// x, y, width, height
//context.fillRect(75, 0, 50, 50);
}
function loop() {
console.log('tick');
for (i in myRect) {
//console.log(x);
context.fillRect(myRect[i].x, myRect[i].y, myRect[i].w, myRect[i].h)
myRect[i].x += myRect[i].speedX;
//context.fillStyle = i.fill;
}
context.clearRect(0, 0, elem.width, elem.height);
//context = elem.getContext('2d');
}
setInterval(loop, 25);
</script>
答案 0 :(得分:1)
您需要在之前清除canvas
,然后将矩形绘制到其中:
context.clearRect(0, 0, elem.width, elem.height);
for (i in myRect) {
context.fillRect(myRect[i].x, myRect[i].y, myRect[i].w, myRect[i].h)
myRect[i].x += myRect[i].speedX;
}