HTML and CSS Reference
In-Depth Information
var dx = mouse.x - arrow.x,
dy = mouse.y - arrow.y,
angle = Math.atan2(dy, dx), //radians
vx = Math.cos(angle) * speed,
vy = Math.sin(angle) * speed;
arrow.rotation = angle;
arrow.x += vx;
arrow.y += vy;
arrow.draw(context);
}());
};
</script>
</body>
</html>
Although this is a complex effect, there shouldn't be anything in here that you don't fully understand by
now. You get the x distance and y distance to the mouse, and from that using
Math.atan2
to get the angle
that forms. You then use that angle to rotate the arrow, and using
Math.cos
and
Math.sin
along with the
speed to find the x and y velocities. Finally, you add the velocities to the position.
Velocity extended
We are entering into dangerous territory here, but this topic takes the definition of velocity into places it
was never meant to go. Although in a strict sense velocity refers to change of position and physical motion
through space, there's no need to limit the concepts you just learned to only the
x
and
y
properties of
objects.
An object you display on the canvas can potentially have a lot of properties to tinker with, and almost all of
them can accept a wide range of values that you can change over time to produce animation. What we
discuss here is the rate of change, or speed, so perhaps
velocity
isn't the best word for it. But the concept
is similar, so we often continue to use the word
velocity
in the variable names when describing something
that changes a property over time.
As an example, we can spin an object around. In this case, you change the object's
rotation
property on
each frame by adding a value to it. You can make the object spin quickly by adding a high value to the
rotation
property on each frame, or have it spin more slowly by adding a smaller value. Correct or not,
we usually refer to the variable that holds the spinning speed as
vr
, for rotational velocity.
Using the familiar
Arrow
class (if you look in its
draw
method, you'll see the
rotation
property is
referenced in the call to
context.rotate
), you can come up with something like this
(05-rotational-
velocity.html)
:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Rotational Velocity</title>
<link rel="stylesheet" href="style.css">
</head>