HTML and CSS Reference
In-Depth Information
onmousemove (use console.log() on the window object to explore the events
available) and then doing some drawing on the canvas at the mouse location. For ex-
ample, the following script records the x, y coordinate of the mouse cursor position and
draws a line from the saved to the current position every time the user moves the mouse,
creating a simple drawing application ( Figure 7-12 ):
// declare global variables
var canvas;
// reference to canvas
element on page
var context;
// reference to canvas
var cwidth;
// reference to canvas
var cheight;
// reference to canvas
var lastX = 0;
// variable to hold an x
coordinate value
var lastY = 0;
// variable to hold an x
coordinate value
// initialize the variables and add event handler
function init() {
canvas = document.getElementById( "canvas" );
context = canvas.getContext("2d");
cwidth = canvas.width;
cheight = canvas.height;
context.strokeStyle = "#000000";
// call the draw function when the cursor moves
over the canvas
canvas.onmousemove = draw;
// draw on the canvas
function draw(e) {
// update the saved x, y coordinates to the po-
sition of the cursor
// if it is first entering the canvas
if (lastX == 0) lastX = e.pageX - can-
Search WWH ::

Custom Search