HTML and CSS Reference
In-Depth Information
and then release. In this chapter, you'll concentrate on those three things: the mouse button going down,
the mouse button going up, and any motion that occurs in between the two.
In our animations, mouse events can be received by the canvas element only from the HTML DOM.
Therefore, it is up to us to determine where the event occurred on the canvas and if it is over a visible
graphic portion of an object drawn to the canvas. In Chapter 2, I showed you to keep track of the mouse
position using the utility function utils.captureMouse . Here, we look for some additional mouse events
on the canvas, and then check whether their position falls within the bounds of our objects. The mouse
events that you need to know are:
mousedown : This event occurs when you press a mouse button while the mouse cursor is over an
HTML element. In the topic examples, this is the canvas element.
mouseup : This event occurs when you release the mouse button while over an element.
mousemove : This event occurs when you move the mouse over an element.
Sometimes you might want to know what the mouse is doing regardless of what HTML element it is over.
In these cases, instead of adding an event listener to the canvas object, you add it to the global window
object.
Let's see if we can use mouse events in our animations. In the next example, you use the same Ball
class from the earlier chapters, but an additional method, Ball.getBounds , has been added. This returns
an object that represents a rectangle containing the shape of the ball on the canvas, or its bounds . The
returned object has the properties x , y , width , and height , and it uses the ball's position and radius to
calculate these. This is what the updated ball.js file looks like:
function Ball (radius, color) {
if (radius === undefined) { radius = 40; }
if (color === undefined) { color = "#ff0000"; }
this.x = 0;
this.y = 0;
this.radius = radius;
this.vx = 0;
this.vy = 0;
this.rotation = 0;
this.scaleX = 1;
this.scaleY = 1;
this.color = utils.parseColor(color);
this.lineWidth = 1;
}
Ball.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.scale(this.scaleX, this.scaleY);
context.lineWidth = this.lineWidth;
context.fillStyle = this.color;
context.beginPath();
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
context.closePath();
 
Search WWH ::




Custom Search