HTML and CSS Reference
In-Depth Information
cos(a + b) = cos(a) * cos(b) - sin(a) * sin(b)
And the corresponding formula for the sine is:
sin(a + b) = sin(a) * cos(b) + cos(a) * sin(b)
So, after expanding the equations for x1 and x2 , we get:
x1 = radius * cos(angle) * cos(rotation) - radius * sin(angle) * sin(rotation)
y1 = radius * sin(angle) * cos(rotation) + radius * cos(angle) * sin(rotation)
Therefore, after we substitute in the x and y variables from above, we have our equation:
x1 = x * cos(rotation) - y * sin(rotation)
y1 = y * cos(rotation) + x * sin(rotation)
We're just using this equation, so it's not necessary for you to understand how we got it, as much as what
it does. So let's see what we can do with it.
Rotating a single object
This example places a single ball at a random location and then uses the advanced coordinate rotation
technique from the previous section to rotate it. It builds on the first example in this chapter, with the added
code in bold (document 02-rotate-2.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Rotate 2</title>
<link rel="stylesheet" href="style.css">
</head>
<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'),
ball = new Ball(),
vr = 0.05,
cos = Math.cos(vr),
sin = Math.sin(vr),
centerX = canvas.width / 2,
centerY = canvas.height / 2;
ball.x = Math.random() * canvas.width;
ball.y = Math.random() * canvas.height;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
 
Search WWH ::




Custom Search