Reputation: 3697
I am building an animation with HTML5 canvas, I'm very new to the language so am learning on the go a little bit.
The animation is to be lines "drawing" from point A to point B to point C to point D etc (13 lines in total).
I have been able to draw the lines with this code:
<canvas id="myCanvas" width="220" height="600"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(0, 2);
// LINE 1
context.lineTo(220, 2);
// LINE 2
context.lineTo(0, 30);
// LINE 3
context.lineTo(220, 30);
// LINE 4
context.lineTo(0, 60);
// LINE 5
context.lineTo(220, 60);
// LINE 6
context.lineTo(0, 90);
// LINE 7
context.lineTo(220, 90);
// LINE 8
context.lineTo(0, 120);
// LINE 9
context.lineTo(220, 120);
// LINE 10
context.lineTo(0, 150);
// LINE 11
context.lineTo(220, 150);
// LINE 12
context.lineTo(0, 180);
// LINE 13
context.lineTo(220, 180);
context.lineWidth = 2;
context.stroke();
</script>
However, now I want to be able to animate the lines one by one. Can anybody help me figure out how I would do this please?
Here is a JSfiddle
Upvotes: 1
Views: 1775
Reputation: 2783
http://jsfiddle.net/6zv7jgo4/1/ and this one for clearing after X lines: http://jsfiddle.net/6zv7jgo4/2/
Use a function to draw the lines, like this:
function drawLine(whichOne, context)
{
context.beginPath();
if (whichOne % 2 == 0)
{
context.moveTo(0,2 + (whichOne / 2) * 30);
context.lineTo(220, 2 + ((whichOne + 1) / 2) * 30);
}
else
{
context.moveTo(220,2 + (whichOne / 2) * 30);
context.lineTo(0, 2 + ((whichOne + 1) / 2) * 30);
}
context.lineWidth = 2;
context.stroke();
}
The function automatically calculates where it should draw, depending on which line you want it to draw.
Then you just use an interval to draw the lines one by one:
var counter = 0;
setInterval(function(){
if (counter > 1000000) {//or any other number
counter = 0;
context.clearRect(0, 0, 220, 600);
}
drawLine(counter,context);
counter++;
},1000);
Full code: see jsfiddle!
Upvotes: 1
Reputation: 624
Use context.stroke() after each context.lineTo() and add a small delay after each context.stroke().
Maybe you can do a function:
function drawLine(x, y) {
context.lineTo(x, y);
context.stroke();
}
Then do:
drawLine(220, 2);
setTimeout(function () {
drawLine(0, 30);
}, 200);
setTimeout(function () {
drawLine(220, 30);
}, 200);
....
Edit:
Also make sure you initialise the context strokewidth in the beginning.
Upvotes: 1