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;
}
Use JavaScript objects to represent multiple rectangles
Here's an outline of how to do it:
x
valueAnnotated code and a Demo:
An improvement I leave for you to do is to stop the animation when all rectangles have left the visible canvas.
This is the point of OOP (Object Orientated Programming), where each item in your program is represented as an object. In your case we can have a
Square
object that has a: x, y, width, and color. Along with a function to draw itselfanim()
:Then you can easily create objects, to animate each one place them inside an array and call
anim()
for each square inobjects
:Fiddle Example