在这段代码中,我有一个从中间左边移动到30tt的矩形,然而,当我试图想要如何添加另一个与反对的大小相同的方块时,我的大脑会受伤,但是从不同的方向。问题是我如何添加多个对象,无论是矩形圆,还是像另一个起始x y位置的正方形一样动画,这是我到目前为止所拥有的:
var rectY=200, rectW=40;
var rectX = -rectW;
var canvas = null;
var context = null;
function init() {
canvas = document.getElementById('testCanvas');
context = canvas.getContext("2d");
blank();
context.fillStyle= "yellow";
context.fillRect(rectX,rectY,rectW,rectW);
setInterval(anim, 30);
}
function blank() {
context.fillStyle = "#00ddee";
context.fillRect(0,0,context.canvas.width, context.canvas.height);
}
function anim() {
if (rectX < context.canvas.width) {
blank();
rectX += 5;
context.fillStyle = "yellow";
context.strokeStyle = "red";
context.lineWidth = 3;
context.fillRect(rectX,rectY,rectW,rectW);
context.strokeRect(rectX,rectY,rectW,rectW);
}
else rectX=-rectW;
}
答案 0 :(得分:5)
使用JavaScript对象表示多个矩形
以下是如何操作的概述:
x
值带注释的代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// define a rect using a javascript object
var rect1={
x:20,
y:20,
width:40,
height:40,
directionX:1
}
// define another rect using a javascript object
var rect2={
x:250,
y:90,
width:40,
height:40,
directionX:-1
}
// put each rect in a rects[] array
var rects=[rect1,rect2];
// start the animation loop
requestAnimationFrame(animate);
function animate(time){
// move each rect in the rects[] array by its
// own directionx
for(var i=0;i<rects.length;i++){
rects[i].x+=rects[i].directionX;
}
// draw all the rects in their new positions
draw();
// request another frame in the animation loop
requestAnimationFrame(animate);
}
function draw(){
ctx.clearRect(0,0,cw,ch);
for(var i=0;i<rects.length;i++){
var r=rects[i]
ctx.strokeRect(r.x,r.y,r.width,r.height);
}
}
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
我留给你的改进是当所有矩形离开可见画布时停止动画。
答案 1 :(得分:1)
这是 OOP (面向对象编程)的要点,程序中的每个项目都表示为一个对象。在您的情况下,我们可以有一个Square
对象,其中包含:x,y,width和color。除了绘制自己的函数anim()
:
function Square(x, y, w, color)
{
this.x = x;
this.y = y;
this.w = w;
this.color = color;
this.anim = function()
{
if (this.x < context.canvas.width) {
this.x += 5;
context.fillStyle = this.color;
context.strokeStyle = "red";
context.lineWidth = 3;
context.fillRect(this.x,this.y,this.w,this.w);
context.strokeRect(this.x,this.y,this.w,this.w);
}
else this.x=-this.w;
}
}
然后,您可以轻松创建对象,为每个对象设置动画,将它们放置在数组中,并为anim()
中的每个方块调用objects
:
var rect1 = new Square(-40, 200, 40, "yellow");
var rect2 = new Square(0, 100, 40, "blue");
var objects = [ rect1, rect2 ];
setInterval(function(){
blank();
for(rect in objects){
objects[rect].anim();
}
}, 30);