Reputation: 807
So, I'm trying to get into HTML5 Canvas with a small project animating an existing header consisting of red laser-like lines bursting from a single point. I'm able to draw these lines as I want them, and animate them as a group at a nice speed, but the next hurdle is above my head, I think: I'd like each line to move independently!
I've got an object defining the starting point for my lines such as:
var myLines = {
a: 1500,
b: 700,
c: 400,
d: 310,
e: 140,
f: 60
}
And I then draw with a loop kinda like:
for (var i in myLines)
{
var cur = myLines[i];
context.beginPath();
context.moveTo(0, canvas.height);
context.lineTo(canvas.width, myLine.y-cur);
context.stroke();
}
Using an awkward method of incrementation:
var step = 1;
if (myLine.y+step > canvas.height) {set = false;}
if (myLine.y-step < 0) {set = true;}
if (set) {
myLine.y = myLine.y+step;
} else {
myLine.y = myLine.y-step;
}
I'm aware the above code is poorly written, I'm out of my league here, I work during the day as a chef in a small kitchen, but I'd like some advice, please!
Here's a fiddle to see it all in action.
Thanks in advance!
Upvotes: 2
Views: 2176
Reputation: 3542
If I were you I would change the script so that each line was a separate object, rather than just an offset. Something like:
var line = { x: 0, y: 0, speed: 1 };
That way each line can have its own speed, and inside your loop, you can do something like the following to add on the speed and flip it when you reach the edge of the screen:
line.x += line.speed;
if(/* edge of screen */) {
line.speed = -line.speed;
}
Upvotes: 1