HTML and CSS Reference
In-Depth Information
In order for the user to be able to draw on the screen, we'll need to be able to track his
cursor motions and clicks within the Canvas. We can do so by adding event listeners
to the
<canvas>
element as follows:
theCanvas.addEventListener('mousedown', mouse_pressed_down, false);
theCanvas.addEventListener('mousemove', mouse_moved, false);
theCanvas.addEventListener('mouseup', mouse_released, false);
Now when a user pressed down on the mouse within the
<canvas>
, a
mousemove
event
is triggered in the browser, and our event listener calls the
mouse_pressed_down
function.
Similarly, when the mouse is moved within the dimensions of the Canvas, the
mouse_moved
function is called, and when the mouse button is released, the
mouse_released
function is called. Let's take a look at these three functions:
function mouse_pressed_down (ev) {
begin_drawing = true;
context.fillStyle = colorChosen.innerHTML;
}
function mouse_moved (ev) {
var x, y;
// Get the mouse position in the canvas
x = ev.pageX;
y = ev.pageY;
if (begin_drawing) {
context.beginPath();
context.arc(x, y, 7, (Math.PI/180)*0, (Math.PI/180)*360, false);
context.fill();
context.closePath();
}
}
function mouse_released (ev) {
begin_drawing = false;
}
The
mouse_pressed_down
function serves to “turn on” a drawing event on the canvas. It
sets the variable
begin_drawing
to
true
, and then sets the fill color to be used to the
current color selected from the color palette.
Then when the
mouse_moved
function is called (which occurs any time the mouse is
moved somewhere within the Canvas), we get the cursor's coordinates using the
pageX
/
pageY
properties. We check if the
begin_drawing
variable is set to
true
, which means
that the user has the mouse button pressed down, and if so, we draw a circle of the
designated color with a radius of 7 pixels at the cursor location.
As long as the mouse button is held down while the mouse is moved over the Canvas,
the
mouse_moved
function will be called every single time the cursor location changes,
which means that circles will continue to be drawn as the mouse moves, resulting in
an effect quite similar to the Paintbrush tool in many image-editing applications.