Skip to content

Instantly share code, notes, and snippets.

@IbrahimTanyalcin
Created September 14, 2018 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IbrahimTanyalcin/2915f7a33d806c1aaa1e024574e47c5f to your computer and use it in GitHub Desktop.
Save IbrahimTanyalcin/2915f7a33d806c1aaa1e024574e47c5f to your computer and use it in GitHub Desktop.
Performance comparsion of SVG point along path - fast version
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>
path {
fill: none;
stroke: #000;
stroke-width: 3px;
}
circle {
stroke: #fff;
stroke-width: 3px;
}
</style>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var points = [
[480, 200],
[580, 400],
[680, 100],
[780, 300],
[180, 300],
[280, 100],
[380, 400]
];
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var path = svg.append("path")
.data([points])
.attr("d", d3.svg.line()
.tension(0) // Catmull–Rom
.interpolate("cardinal-closed"));
svg.selectAll(".point")
.data(points)
.enter().append("circle")
.attr("r", 4)
.attr("transform", function(d) { return "translate(" + d + ")"; });
var colorScale = d3.scale.category20().domain(Array.apply(null,Array(20)).map(function(d,i){return i}));
var circle = svg.selectAll("some").data(d3.range(100)).enter().append("circle")
.attr("r", function(d,i){return 10+Math.random()*10})
.attr("fill",function(d,i){return colorScale(i)})
.attr("transform", "translate(" + points[0] + ")");
transition();
function transition() {
var counter = 0;
circle.each(function(d,i){
counter++;
d3.select(this).transition()
.duration(function(){return 2080 + i * 80})
.tween("transform", translateAlong(path.node()))
.each("end", function(){
--counter;
if(!counter){transition();}
});
})
}
// Returns an attrTween for translating along the specified path element.
function translateAlong(path){
var points = path.__points || collectPoints(path);
return function (d,i){
var transformObj = this.transform.baseVal[0];
return function(t){
var index = t * 1000 | 0,
point = points[index];
transformObj.setTranslate(point[0],point[1]);
}
}
}
function collectPoints(path) {
var l = path.getTotalLength(),
step = l*1e-3,
points = [];
for(var i = 0,p;i<=1000;++i){
p = path.getPointAtLength(i*step);
points.push([p.x,p.y]);
}
return path.__points = points;
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment