HTML and CSS Reference
In-Depth Information
y axis
Figure 15-11. Rotation on the y axis
Thus, for 3D, when you rotate an object on one axis, its position changes on the other two axes.
In Chapter 10, we calculated 2D coordinate rotation using the formula:
x1 = x * cos(angle) - y * sin(angle)
y1 = y * cos(angle) + x * sin(angle)
In 3D, you do basically the same thing, but you need to specify which angle you're talking about: x, y, or z.
Thus, you get the following three formulas:
x1 = x * cos(angleZ) - y * sin(angleZ)
y1 = y * cos(angleZ) + x * sin(angleZ)
x1 = x * cos(angleY) - z * sin(angleY)
z1 = z * cos(angleY) + x * sin(angleY)
y1 = y * cos(angleX) - z * sin(angleX)
z1 = z * cos(angleX) + y * sin(angleX)
We'll perform a y-axis rotation in the next example, 12-rotate-y.html . It creates 50 instances of Ball3d
and randomly positions them. Then, it gets a y angle based on the mouse's x position. The farther right the
mouse goes, the higher the number for the angle. This makes the objects seem to follow the mouse in
their rotation.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Rotate Y</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball3d.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
Search WWH ::




Custom Search