Skip to content

Instantly share code, notes, and snippets.

@mikolalysenko
Last active December 17, 2015 08:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikolalysenko/5580867 to your computer and use it in GitHub Desktop.
Save mikolalysenko/5580867 to your computer and use it in GitHub Desktop.
Spring!
//Config variables
var rest_length = 256.0
var spring_constant = 1.0
var dt = 0.01
//Hooke's law
function force(displacement) {
return spring_constant * (rest_length - displacement)
}
//State of system
var x = 0.0
var v = 0.0
//Integrate forward by dt
function step() {
var f = force(x)
x += (v + f * 0.5 * dt) * dt
v += (f + force(x)) * 0.5 * dt
}
//Set up canvas
var canvas = document.createElement("canvas")
canvas.width = 512
canvas.height = 512
document.body.appendChild(canvas)
var context = canvas.getContext("2d")
//Animate!
setInterval(function() {
context.clearRect(0, 0, 512, 512)
context.fillStyle = "rgba(0,0,0,255)"
context.beginPath()
context.arc(x, 256, 10, 0, Math.PI*2, true);
context.closePath();
context.fill()
step()
}, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment