HTML and CSS Reference
In-Depth Information
When the mouse button is released, the begin_drawing variable is set back to false ,
which “turns off” the drawing event. This ensures that drawing occurs only when the
mouse is held down, and not when the mouse is moved over the Canvas without the
button being pressed.
The above code works great on desktop and laptop browsers, where a mouse is used
to interface with screen elements, but what about touchscreen devices like the iPad? In
general, touchscreen browsers do not support mousedown / mousemove / mouseup events, as
there is no mouse button or mouse cursor that they can track; all those features are
replaced with finger taps and swipes. However, WebKit - based browsers support a cor-
responding set of events for tracking finger motions in the browser: touchstart / tou
chend / touchmove . So we can implement the same drawing functionality as above using
a touchmove event listener:
theCanvas.addEventListener('touchmove', touch_move_gesture, false);
And the following touch_move_gesture function:
function touch_move_gesture (ev) {
// For touchscreen browsers/readers that support touchmove
var x, y;
context.fillStyle = colorChosen.innerHTML;
if(ev.touches.length == 1){
var touch = ev.touches[0];
x = touch.pageX;
y = touch.pageY;
context.arc(x, y, 7, (Math.PI/180)*0, (Math.PI/180)*360, false);
The touchmove handling for touchscreen devices is actually much sim-
pler than the mouse-based version, because we don't even need to track
touchstart and touchend events. When dealing with a mouse, we need
to keep track of whether the mouse button is pressed or not when it's
being moved on the canvas. In the touch version, we know that if the
touchmove event has been triggered, the user has his finger on the screen
and is intending to draw.
And that's the meat of the finger painting code. All that's left is the code to initialize
the event listeners, track color palette selections, and implement the Reset Drawing
button functionality. Example 1-1 shows the full JavaScript code for our finger painting
Example 1-1. Finger painting JavaScript code ( finger_painting.js )
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
Search WWH ::

Custom Search