【发布时间】:2014-02-20 22:32:45
【问题描述】:
你好 :) 我花了很多时间来弄清楚如何实现我的代码。我在数组中有一组对象(随机矩形)。我想让它们像一个物体一样从左到右和从右到左同时移动。但在一切之前,我不知道如何让它们作为一个物体移动......任何帮助将不胜感激。谢谢。
<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>
【问题讨论】:
标签: javascript html animation canvas setinterval