How to progressively draw line animation in html5 canvas
10,552
<!DOCTYPE html>
<html>
<head>
<title>Parent selector</title>
</head>
<body>
<canvas height="300px" width="500px" id="canva"></canvas>
<script>
var canva = document.getElementById('canva'),
ctx = canva.getContext('2d');
var Point = function (x, y) {
this.startX = x;
this.startY = y;
};
var points = [new Point(1, 2),
new Point(10, 20),
new Point(30, 30),
new Point(40, 80),
new Point(100, 100),
new Point(120, 100)];
//goto first point
ctx.strokeStyle = "black";
ctx.moveTo(points[0].startX, points[0].startY);
var counter = 1,
inter = setInterval(function() {
//create interval, it will
//iterate over pointes and when counter > length
//will destroy itself
var point = points[counter++];
ctx.lineTo(point.startX, point.startY);
ctx.stroke();
if (counter >= points.length) {
clearInterval(inter);
}
console.log(counter);
}, 500);
ctx.stroke();
</script>
</body>
</html>
Author by
Jaya
Updated on June 08, 2022Comments
-
Jaya almost 2 years
I am working with canvas. I have draw a set of lines. Here is my sample code
for(var i = 0 ; i< points.length; i++){ var point = points[i]; setInterval(function() { ctx.strokeStyle = "black"; ctx.moveTo(point.startX, point.startY); ctx.lineTo(point.startX1, point.startY1); ctx.stroke(); }, 500); }
This code draws line after every 0.5 seconds. But I wish to animate it progressively. So kindly help to draw a line progressively.
This screen shot show the output. I made this possible in SVG. But I need the same in canvas.
-
Jaya over 9 yearsHi Sorry.. :( This is what my code does. Draw a line, after 500ms delay draw another line and so on.. But i need like progressive as like in screen shot. Could you suggest any other way if possible ??
-
Ivan Ivanov over 9 yearsSee upd. There is no background and other features. But it progressively draws diagram. More detailed questions, please.
-
Jaya over 9 yearsYa.. As I mentioned, that is generated in SVG using jquery's animate method. I am in need of any other approach which bring this o/p other than setInterval. Its just an reference, background doesn't matters. I just saying about the line. Thanks.