Skip to content

Instantly share code, notes, and snippets.

@1wheel
Last active August 22, 2016 02:21
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 1wheel/732f86cf0f4061fa37e1 to your computer and use it in GitHub Desktop.
Save 1wheel/732f86cf0f4061fa37e1 to your computer and use it in GitHub Desktop.
elastic-snap

Playing around with parameters for a snapping effect

var width = 960,
height = 500
var svg = d3.select('html')
.append('svg')
.attr({width: width, height: height})
.on('mousemove', updatePos)
svg.append('rect')
.attr({width: width, height: height, opacity: 0})
var circle = svg.append('circle')
.attr('r', 10)
.attr('cx', width/2)
.attr('cy', height/2)
.style({stroke: 'black', fill: 'lightgrey', 'stroke-width': 2})
var vel = 0
var cx = width/2
var mx = width
var speedCap = 10
d3.timer(function(){
var dist = mx - cx
var absDist = Math.abs(dist)
vel += (mx - cx)/1000
vel = clamp(-absDist/speedCap, vel, absDist/speedCap)
cx += vel
circle.attr('cx', cx)
})
function updatePos(){
var pos = d3.mouse(this)
mx = pos[0]
speedCap = pos[1]/height*40
}
function clamp(a, b, c){ return Math.max(a, Math.min(b, c)) }
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg{
overflow: visible;
margin: 0px auto;
display: block;
}
html{
width: 960px;
height: 500px;
}
</style>
<script src="/1wheel/raw/67b47524ed8ed829d021/d3-3.5.5.js"></script>
<script src="/1wheel/raw/67b47524ed8ed829d021/lodash-3.8.0.js"></script>
<script src='/1wheel/raw/1b6758978dc2d52d3a37/d3-jetpack.js'></script>
<script src='/1wheel/raw/1b6758978dc2d52d3a37/d3-starterkit.js'></script>
<script src='/1wheel/raw/5d32ecb8a54b42f53646/geometry.js'></script>
<script src='elastic-ease.js'></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment