HTML and CSS Reference
In-Depth Information
centerY = canvas.height / 2;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball.x = centerX + Math.cos(angle) * radius;
ball.y = centerY + Math.sin(angle) * radius;
angle += vr;
ball.draw(context);
}());
};
</script>
</body>
</html>
This approach works great when you know the angle and radius from a center point.
But what if you only have the position of the object and the center point? Well, it isn't too hard to calculate
the current angle and radius based on the x and y positions. Once you have them, you can carry on as
before. Figure 10-2 shows the general layout of our calculation, and here's the code:
var dx = ball.x - centerX,
dy = ball.y - centerY,
angle = Math.atan2(dy, dx),
radius = Math.sqrt(dx * dx + dy * dy);
ball.x,
ball.y
dy
(ball.y - centerY)
centerX,
centerY
angle
dx
(ball.x - centerX)
Figure 10-2. Getting ready to calculate the angle and radius.
This method of coordinate rotation is fine for a single object, especially in a situation where you only need
to determine the angle and radius once. But in a more dynamic example, you could have many objects to
rotate, and their relative positions to the center rotation point could be changing. So, for each object, you
would need to compute its distance, angle, and radius, then add the vr to the angle, and finally calculate
the new x, y position, on each frame. This is neither elegant, nor efficient, but fortunately, there is a better
way.
 
Search WWH ::




Custom Search