A (not so) simple d3-inertia example.
The offset is t * (1-t) * velocity
, which allows the drawing to come back to its original place after n seconds.
license: mit |
A (not so) simple d3-inertia example.
The offset is t * (1-t) * velocity
, which allows the drawing to come back to its original place after n seconds.
<!doctype html> | |
<html> | |
<head> | |
<script src="https://unpkg.com/d3"></script> | |
<script src="https://unpkg.com/d3-inertia"></script> | |
<style> | |
svg { | |
cursor: move; /* fallback if grab cursor is unsupported */ | |
cursor: grab; | |
} | |
</style> | |
</head> | |
<body> | |
<svg></svg> | |
<script> | |
const width = 960, height = 500, margin = 10; | |
const svg = d3.select("svg").attr('width', width).attr('height', height); | |
var dots = d3.range(100) | |
.map(d => | |
[Math.random()*width, Math.random()*height, 0.2 * (0.5 - Math.random()) * 2 * Math.PI] | |
); | |
svg.selectAll('circle') | |
.data(dots) | |
.enter() | |
.append('circle') | |
.attr('cx', d => d[0]) | |
.attr('cy', d => d[1]) | |
.attr('r', d => Math.random() * 50) | |
.attr('fill-opacity', 0.1) | |
.attr('fill', d => d[2] > 0 ? 'orange' : 'pink') | |
.attr('stroke', 'lightblue') | |
function draw(offset) { | |
svg.selectAll('circle') | |
.attr('cx', d => d[0] + offset[0] * Math.cos(d[2]) + offset[1] * Math.sin(d[2])) | |
.attr('cy', d => d[1] + offset[1] * Math.cos(d[2]) - offset[0] * Math.sin(d[2])) | |
} | |
var n = 10000; // reference time in ms | |
var position = [0,0], startposition, endposition; | |
var inertia = d3.inertiaHelper({ | |
start: function(){ | |
startposition = inertia.position; | |
}, | |
move: function(){ | |
draw([position[0] + inertia.position[0] - startposition[0], | |
position[1] + inertia.position[1] - startposition[1]]) | |
}, | |
end: function(){ | |
position = endposition = [position[0] + inertia.position[0] - startposition[0], | |
position[1] + inertia.position[1] - startposition[1]] | |
}, | |
render: function(t) { | |
position = [endposition[0] + t * (1-t) * inertia.velocity[0], | |
endposition[1] + t * (1-t) * inertia.velocity[1]]; | |
draw(position) | |
}, | |
time: n | |
}); | |
svg.call( | |
d3.drag() | |
.on("start", inertia.start) | |
.on("drag", inertia.move) | |
.on("end", inertia.end) | |
); | |
</script> | |
</body> | |
</html> |