A 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.
forked from Fil's block: Inertia and back
xxxxxxxxxx
<html>
<head>
<script src="https://unpkg.com/d3"></script>
<script src="https://unpkg.com/d3-inertia"></script>
<style>
.eclipses path {
fill: #666;
fill-opacity: 0.6;
}
#sphere {
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('id', 'sphere')
.attr('width', width)
.attr('height', height);
var dots = [[100, 220],
[100, 340]];
svg.selectAll('circle')
.data(dots)
.enter()
.append('circle')
.attr('cx', d => d[0])
.attr('cy', d => d[1])
.attr('r', d => 50)
.attr('fill-opacity', 1)
.attr('fill', 'orange')
.attr('stroke','lightblue')
function draw(offset) {
const cos = Math.cos(50);
const sin = Math.sin(50);
svg.selectAll('circle')
.attr('cx', d => d[0] + offset[0] * cos + offset[1] * sin)
.attr('cy', d => d[1] + offset[1] * cos - offset[0] * sin)
}
var n = 10000; // reference time in ms
var position = [0,0], startposition, endposition;
var inertia = d3.inertia({
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>
https://unpkg.com/d3
https://unpkg.com/d3-inertia