HTML and CSS Reference
In-Depth Information
Figure 4-13. The Tile Stamper application
The screen is broken up into two sections vertically. The top section is the 256×128 tile
sheet; the bottom is a tile map of the same size. The user will select a tile in the top
section, and it will be highlighted by a red square. The user can then stamp the selected
tile to the tile map drawing area in the lower portion. When a tile is drawn in this lower
portion, we will set its alpha value to 128 .
Adding mouse events to the canvas
We need to code our application to respond to mouse clicks and to keep track of the
current x and y positions of the mouse pointer. We will set up two global application
scope variables to store the mouse pointer's current position:
var mouseX;
var mouseY;
We will also set up two event listener functions and attach them to the theCanvas object:
theCanvas.addEventListener("mousemove", onMouseMove, false);
theCanvas.addEventListener("click", onMouseClick, false);
In the HTML, we will set up a single Canvas object:
<canvas id="canvas" width="256" height="256" style="position: absolute;
top: 50px; left: 50px;">
Your browser does not support HTML5 Canvas.
</canvas>
In the JavaScript portion of our code, we will define the canvas:
theCanvas = document.getElementById("canvas");
Notice that we set the <canvas> position to top: 50px and left: 50px . This will keep
the application from being shoved up into the top-left corner of the browser, but it also
gives us a chance to demonstrate how to find correct mouse x and y values when the
<canvas> tag is not in the top-left corner of the page. The onMouseMove function will
 
Search WWH ::




Custom Search