HTML5 canvas绘制在画布中移动的多个矩形 [英] HTML5 canvas draw multiple rectangles that move in the canvas
问题描述
在这段代码中,我有一个矩形从中间左边移动到右边30点,但是,我的大脑伤害,当我试图去想添加另一个方形大小相同的大小作为一个antimated,但开始从不同的方向。问题是我可以添加多个对象,无论是矩形圆,并让它像另一个起始的xy位置的广场动画。这里是我迄今为止:
In this code i have a rectangle moving from the middle-left to the right at 30ticks, however, my brain hurts when i try to think how im going to add another square about the same size as the one antimated, but starting from a different direction. The issue is how i can add multiple objects, whether rectangle-circle and have it animate like the square in another starting x y location, here's what i have so far:
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;
}
推荐答案
- 使用javascript对象描述每个矩形
- 将每个rect对象放在rects []数组中
- :
- 更改每个rect的
x
值
- Use a javascript object to describe each of your rectangles
- Put each rect object in a rects[] array
- Inside an animation loop:
- Change each rect's
x
value - Redraw the canvas with the rects in their new positions
- Request another loop in the animation
注释代码和演示:
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); } }
body{ background-color: ivory; } #canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
你可以做的是当所有矩形都离开可见的画布时停止动画。
An improvement I leave for you to do is to stop the animation when all rectangles have left the visible canvas.
这篇关于HTML5 canvas绘制在画布中移动的多个矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Change each rect's
- 更改每个rect的