Bouncing ball with fixed trail. Click anywhere to pause/resume.
See example 1.1 in the Nature of Code.
Bouncing ball with fixed trail. Click anywhere to pause/resume.
See example 1.1 in the Nature of Code.
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<script src="http://jashkenas.github.io/coffee-script/extras/coffee-script.js"></script> | |
<script src="https://s3-eu-west-1.amazonaws.com/svgjs/svg.js"></script> | |
<body> | |
<div id="canvas"></div> | |
<script type="text/coffeescript"> | |
runTime = 5 # running time in seconds | |
w = 960 # canvas width | |
h = 500 # canvas height | |
d = 50 # diameter of bug | |
trail = [] # trail of markers | |
trailLength = 50 | |
draw = SVG('canvas').size(w, h) | |
border = draw.rect(w, h) | |
.attr | |
fill: "none" | |
stroke: "#999" | |
'stroke-width': 3 | |
class Point | |
constructor: (@x, @y) -> | |
velocity = new Point 5, 6 | |
begin = new Point d/2, d,2 | |
mark = (x, y) -> | |
draw.circle(2) | |
.center(x, y) | |
.back() | |
.attr fill: "#999" | |
bug = draw.circle(d) | |
.center(begin.x, begin.y) | |
.attr | |
id: "bug" | |
fill: "aliceblue" | |
stroke: "steelblue" | |
'stroke-width': 5 | |
borderColor = (color) -> | |
border.attr | |
stroke: color | |
reverse = -> | |
borderColor "orange" | |
setTimeout (-> borderColor "#999"), 100 | |
-1 | |
move = => | |
trail.push mark(bug.cx(), bug.cy()) | |
trail.shift().remove() if trail.length > trailLength | |
x = bug.x() | |
y = bug.y() | |
velocity.x *= reverse() if (x+d > w) or (x < 0) | |
velocity.y *= reverse() if (y+d > h) or (y < 0) | |
bug.move(x+velocity.x, y+velocity.y) | |
paused = false | |
# enable toggling of animation with a click | |
toggle = -> | |
if paused | |
paused = false | |
run() | |
else | |
paused = true | |
canvas = document.getElementById("canvas") | |
canvas.addEventListener('click', toggle); | |
run = -> | |
move() | |
return if paused | |
requestAnimationFrame(run) | |
runFor = (secs=10) -> | |
setTimeout (-> paused = true), secs * 1000 | |
run() | |
runFor runTime | |
</script> |