HTML and CSS Reference
In-Depth Information
<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(),
xpos = 0,
ypos = 0,
zpos = 0,
fl = 250,
vpX = canvas.width / 2,
vpY = canvas.height / 2;
window.addEventListener('keydown', function (event) {
if (event.keyCode === 38) { //up
zpos += 5;
} else if (event.keyCode === 40) { //down
zpos -= 5;
}
}, false);
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var scale = fl / (fl + zpos);
xpos = mouse.x - vpX;
ypos = mouse.y - vpY;
ball.scaleX = ball.scaleY = scale;
ball.x = vpX + xpos * scale;
ball.y = vpY + ypos * scale;
ball.draw(context);
}());
};
</script>
</body>
</html>
First, you create variables for
xpos
,
ypos
, and
zpos
, as well as
fl
. Then you create a vanishing point,
vpX
,
vpY
. Remember, as objects move off in the distance, they converge on 0, 0. If you don't offset this
somehow, everything converges at the top-left corner of the screen, which is not what you want. You use
vpX
,
vpY
to make the center of the canvas element the vanishing point.
Next, add a listener for the
keydown
event that changes the
zpos
variable. If the up key is pressed,
zpos
increases, and pressing the down key decreases it. This makes the ball move farther from, or closer to, the
viewer.
In the
drawFrame
animation loop, set
xpos
and
ypos
to the mouse position, as offset by the vanishing
point. In other words, if the mouse is 200 pixels right of center,
xpos
is 200. If it's 200 pixels left of center,
xpos
is -200.