HTML and CSS Reference
In-Depth Information
objects. A short focal length is like a wide-angle lens, where you see a lot of the scene, but with a lot of
distortion. A medium focal length approximates what the human eye sees, and uses a value for fl that's
between 200 and 300. Here's the perspective formula:
scale = fl / (fl + z)
This usually yields a number between 0.0 and 1.0, which is your ratio for scaling and converging on the
vanishing point. However, as z approaches -fl , (fl + z) approaches 0 and scale approaches infinity.
This is the coding equivalent to being poked in the eye.
What do you do with this scale value? Well, you can adjust the scale of the canvas context before drawing
the object. For example, in the Ball class we've used throughout the topic, there are scaleX and scaleY
properties that are referenced in its draw method, like so:
context.scale(this.scaleX, this.scaleY);
Once the scale as been determined, you multiply the object's x and y position by this factor to find its
screen x and y position.
Let's look at an example where we use 250 as the focal length. If z is zero—in other words, the object is
exactly on the picture plane—then the scale will be 250 / (250 + 0). This comes out to exactly 1.0. That's
your scaleX and scaleY (remember that for scale, 1.0 means 100%). Multiplying 1.0 by the object's x and
y positions gives the same numbers back as a result, so the object's screen position is exactly equal to its
x and y.
Now move it out so that z is 250. That makes the scale equal to 250 / (250 + 250), or 0.5 for scaleX and
scaleY. It also moves the object's screen position. If the object were at 200, 300 on the x and y axis, its
screen position would now be 100, 150—it has moved halfway to the vanishing point. (Actually, the screen
position would be in relation to the vanishing point, which you see shortly.)
Move z out to 9750. This makes the scale equal to 250/10000, or 0.025 for scaleX and scaleY. The
object becomes just a speck that is close to the vanishing point.
Now we see how to write all of this in code.
Programming perspective
We use the Ball class again for these examples, and for interaction, let's get fancy and use the mouse
and keyboard. The mouse controls the ball's x and y position, and the up and down keys on the keyboard
move the ball forward and back on the z-axis. The variables xpos , ypos , and zpos are used to represent
the 3D position. Here's the code for example 01-perspective-1.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Perspective 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
 
Search WWH ::




Custom Search