Trying to improve the performance of animating lots of SVG paths by dynamically creating CSS animations for each element.
See also: Single path dasharray, Canvas line animation
Trying to improve the performance of animating lots of SVG paths by dynamically creating CSS animations for each element.
See also: Single path dasharray, Canvas line animation
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
path { | |
stroke-width: 2px; | |
fill: none; | |
} | |
</style> | |
<svg width="960" height="500"></svg> | |
<script src="//d3js.org/d3.v4.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500; | |
var svg = d3.select("svg"); | |
var paths = svg.selectAll("path") | |
.data(generateLines(40, 300)) | |
.enter() | |
.append("path") | |
.style("stroke", function(d, i){ | |
return d3.interpolateRainbow(i / 40); | |
}) | |
.attr("d", function(d){ | |
return "M" + d.join("L"); | |
}); | |
paths.each(function(d){ | |
d.len = this.getTotalLength(); | |
}); | |
var style = document.styleSheets[0]; | |
paths.data().forEach(function(line, i){ | |
var rule = style.insertRule("@keyframes dash" + i + "{}", 0), | |
start = "0," + line.len, | |
end = line.len + ",0"; | |
style.cssRules[0].appendRule("0% { stroke-dasharray: " + start + "; } "); | |
style.cssRules[0].appendRule("50% { stroke-dasharray: " + end + "; } "); | |
style.cssRules[0].appendRule("100% { stroke-dasharray: " + start + "; } "); | |
}); | |
paths.style("animation", function(d, i){ | |
return "dash" + i + " 3s linear infinite"; | |
}); | |
function generateLines(numLines, pointsPerLine) { | |
return d3.range(numLines).map(function(i){ | |
var amplitude = ((i + 1) / numLines) * height / 2; | |
return d3.range(pointsPerLine).map(function(j){ | |
var progress = j / (pointsPerLine - 1); | |
return [progress * width, height / 2 + Math.sin(4 * Math.PI * progress) * amplitude]; | |
}); | |
}); | |
} | |
</script> |
Hey Noah,
I've been studying your blocks a lot recently and they've inspired me to learn d3 myself. I read this article by Mike Bostock on how to create blocks but I was wondering if in addition to this you used any particular IDE when writing your own (i.e. to catch syntax errors early etc.)? Just figured I would ask... thanks a lot for sharing this great code. :)
Alex