Implementing the handleMouseDown function

The following code is the source code of the handleMouseDown function, which is used to handle the mousedown event:

function handleMouseDown(event) {
  color = colors[(index++) % colors.length];
  stroke = Math.round(Math.random() * 30 + 10);
  oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
  oldMidPt = oldPt;
  stage.addEventListener("stagemousemove", handleMouseMove);
}

This function is used to handle the mousedown event and will be called after pressing the mouse button. Inside this function, we set the color and size of a stroke, and hold the current mouse position to use in the next function call.

All variables are global, so you can't see any var keyword before them in order to have the variables in the following function calls and other scopes. In the last line, a function also sets the mousemove event in order to manage the drawing lines. Actually, the mousemove event fires whenever the mouse cursor moves in stage.

The color of the brush is selected from the colors array that is defined in the init function, one after the other, using the index variable. What we do to select the next color from the array is increase the index variable and then calculate the division's remainder. With this simple hack, we can choose a value between zero and the length of the array.

The size of the brush is selected using the random function. The random function from the Math class in JavaScript returns a value between 0 and 1 (but not 1). By multiplying this value with 30, we can get a value between 0 and 30 (but not 30). The round function also rounds up a number in JavaScript.

And the important part of that code is that stage.mouseX and stage.mouseY return the current mouse coordinate on the Canvas element. We use those variables to get the mouse position and hold it in a global variable. These values will be used to draw the lines and the reason we save them in a global variable is to provide accessibility in other scopes and functions. As you can see, we used the Point class to collect the coordinate of the mouse cursor. The Point class represents a two-dimensional coordinate system in EaselJS and we use this class to save the cursor pointer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.183.153