你好:)我花了很多时间来弄清楚如何实现我的代码。我在数组中有一组对象(随机矩形)。我想让它们像一个物体一样从左到右和从右到左同时移动。但在这一切之前,我不知道如何让它们作为一个物体移动......任何帮助将不胜感激。谢谢。
<html>
<head>
<meta charset="utf-8" />
<title>Canvas Demo</title>
<script>
window.onload = function () {
function Shape(x, y, w, h, fill) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
// get canvas element.
var elem = document.getElementById('paper');
// check if context exist
if (elem.getContext) {
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"));
context = elem.getContext('2d');
for (var i in myRect) {
oRec = myRect[i];
context.fillStyle = oRec.fill;
context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
}
}
var posX= 0;
setInterval( function(){
posX +=1;
oRec = myRect[i];
context.fillStyle = oRec.fill;
context.fillRect(oRec.posX, oRec.y, oRec.w, oRec.h);
}, 40); };
</script>
<style>
</style>
</head>
<body>
<canvas id="paper" width="500" height="500">
</canvas>
</body>
</html>
最佳答案
我不知道你想要什么动画。
无论如何,我改变了一些你的代码:
function Shape(x, y, w, h, fill) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.fill = fill;
}
var elem=document.getElementById('paper'),myRect=[],context,posX=0;
if(elem.getContext){
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"));
context=elem.getContext('2d');
}
function animate(){
context.clearRect(0,0,context.canvas.width,context.canvas.height);
posX++;
var i=myRect.length;
while(i--){
var oRec=myRect[i];
context.fillStyle=oRec.fill;
context.fillRect(oRec.x+posX, oRec.y, oRec.w, oRec.h);
}
webkitRequestAnimationFrame(animate);//delete if you use setinterval
}
//setInterval(animate,1000);
webkitRequestAnimationFrame(animate);//delete if you use setinterval
如您所见,我正在使用requestAnimationFrame
。这比 setInterval
或 setTimeout
更好。
我还创建了一个自定义函数来为这些东西设置动画......您可以根据需要进行更改。
如果您有任何疑问,请提出。
演示
顺便说一句,如果你的动画形状不超过 100 个,你应该使用 css ...这更简单。
示例
关于javascript - 对 Canvas 中的一组对象设置间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21425717/