I want to animate a progressive drawing of a line using only css with svg/canvas and js maximum. An idea of the line I want to draw can be found here
There are three techniques listed in this answer:
There is an all-SVG solution that involves progressively modifying the stroke-dasharray for the shape to draw a longer and longer 'dash' followed by an enormous gap.
Relevant code:
var distancePerPoint = 1;
var drawFPS = 60;
var orig = document.querySelector('path'), length, timer;
orig.addEventListener('mouseover',startDrawingPath,false);
orig.addEventListener('mouseout', stopDrawingPath, false);
function startDrawingPath(){
length = 0;
orig.style.stroke = '#f60';
timer = setInterval(increaseLength,1000/drawFPS);
}
function increaseLength(){
var pathLength = orig.getTotalLength();
length += distancePerPoint;
orig.style.strokeDasharray = [length,pathLength].join(' ');
if (length >= pathLength) clearInterval(timer);
}
function stopDrawingPath(){
clearInterval(timer);
orig.style.stroke = '';
orig.style.strokeDasharray = '';
}
Alternatively, you can still use all SVG and choose to build the SVG path one command at a time:
Relevant code:
// Assumes 'orig' and dup' are SVG paths
function addNextPathSegment(){
var nextIndex = dup.pathSegList.numberOfItems;
if (nextIndex
Finally, you may choose to draw your path to an HTML5 canvas by sampling the SVG path periodically and drawing to the canvas. (Note that the SVG path does not need to be displayed for this to happen; you can build an SVG path element entirely in JavaScript and sample it):
Relevant code:
function startDrawingPath(){
points = [];
timer = setInterval(buildPath,1000/drawFPS);
}
// Assumes that 'orig' is an SVG path
function buildPath(){
var nextPoint = points.length * distancePerPoint;
var pathLength = orig.getTotalLength();
if (nextPoint <= pathLength){
points.push(orig.getPointAtLength(nextPoint));
redrawCanvas();
} else stopDrawingPath();
}
function redrawCanvas(){
clearCanvas();
ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for (var i=1;i