Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
68 lines (61 sloc) 1.85 KB
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Chain Array</title>
<link rel="stylesheet" href="../include/style.css">
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="400" height="400"></canvas>
<aside>Move mouse on canvas element.</aside>
<script src="../include/utils.js"></script>
<script src="./classes/ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
balls = [],
numBalls = 5,
spring = 0.03,
friction = 0.9,
gravity = 2;
while (numBalls--) {
balls.push(new Ball(20));
}
function move (ball, targetX, targetY) {
ball.vx += (targetX - ball.x) * spring;
ball.vy += (targetY - ball.y) * spring;
ball.vy += gravity;
ball.vx *= friction;
ball.vy *= friction;
ball.x += ball.vx;
ball.y += ball.vy;
}
function draw (ballB, i) {
//if first ball, move to mouse
if (i === 0) {
move(ballB, mouse.x, mouse.y);
context.moveTo(mouse.x, mouse.y);
} else {
var ballA = balls[i-1];
move(ballB, ballA.x, ballA.y);
context.moveTo(ballA.x, ballA.y);
}
context.lineTo(ballB.x, ballB.y);
context.stroke();
ballB.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
balls.forEach(draw);
}());
};
</script>
</body>
</html>