HTML and CSS Reference
In-Depth Information
theCanvas = document.getElementById("canvasOne");
context = theCanvas.getContext("2d");
setInterval(drawScreen, 33);
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support HTML5 Canvas.
Moving on a Vector
Moving between two points is handy, but sometimes you don't have a point to move
to, only a point to start from. In cases like this, it can be very useful to create a vector
as a means to move your object.
A vector is a quantity in physics that has both magnitude and direction. For our pur-
poses, the magnitude will be the speed of the moving object, and the direction will be
an angle that the object will move upon.
The good news is that moving on a vector is very similar to moving between two points.
In canvasApp() , we first set our speed (magnitude). This is the number of pixels the
object will move on every call to drawScreen() . We will set this to 5 . We will also set
the starting point ( p1 ) for the object to 20 , 20 :
var speed = 5;
var p1 = {x:20,y:20};
Now, we will set the angle (direction) of movement for our object to 45 degrees. In
mathematics, a flat, straight line usually represents the 0 angle, which means a vector
with an angle of 45 degrees would be down and to the right on the canvas.
With our angle set, we now need to convert it to radians. Radians are a standard unit
of angle measurement, and most mathematical calculations require you to convert an
angle into radians before you can use it.
So why not just use radians and forget degrees altogether? Because it is much easier to
understand movement in degrees when working with vectors and moving objects on a
2D surface. While a circle has 360 degrees, it has just about 6 radians, which are cal-
culated counterclockwise. This might make perfect sense to mathematicians, but to
move objects on a computer screen, angles are much easier. So, we will work with
Search WWH ::

Custom Search