Skip to content

Instantly share code, notes, and snippets.

@Fil
Last active January 1, 2020 16:19
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 Fil/a034e32156b7b25ee9054c1bc50dc0ca to your computer and use it in GitHub Desktop.
Save Fil/a034e32156b7b25ee9054c1bc50dc0ca to your computer and use it in GitHub Desktop.
Inertia and back
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment