HTML and CSS Reference
In-Depth Information
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
ball = new Ball(),
spring = 0.03,
friction = 0.9,
springLength = 100,
vx = 0,
vy = 0;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = ball.x - mouse.x,
dy = ball.y - mouse.y,
angle = Math.atan2(dy, dx),
targetX = mouse.x + Math.cos(angle) * springLength,
targetY = mouse.y + Math.sin(angle) * springLength;
vx += (targetX - ball.x) * spring;
vy += (targetY - ball.y) * spring;
vx *= friction;
vy *= friction;
ball.x += vx;
ball.y += vy;
context.beginPath();
context.moveTo(ball.x, ball.y);
context.lineTo(mouse.x, mouse.y);
context.stroke();
ball.draw(context);
}());
};
</script>
</body>
</html>
Even though you can see what is happening here, it might not be obvious where you would find this
technique useful. Well, the next section will give you a specific example.
Attaching multiple objects with springs
Since we know how to spring an object to a point, and that the point does not have to be fixed. You could
have one object spring to another object, and have the other object spring back to the first one, so that
these two objects are linked together by a spring. Move either one, and the other object springs to it.
 
Search WWH ::




Custom Search