8bitrocket.com
14Dec/110

HTML5 Canvas Christmas Tree Drag And Drop Demo And Tutorial

Here is another demo from DevCon5.  Yesterday we showed you an action game, now we will show you something completely different.  A Drag And Drop style decoration application of the type we produced by the dozens ta Mattel throughout the first 10 years of this century.  We present to you: Christmas Tree Decorator.  Music by Mike Peters/The Children Of The Revolution.   This was developed for Google chrome and has not been optimized for other browsers yet.

One of the most interesting thing about this demo (to us) is that we display the mouse button pointer when rolling over things that can be clicked and dragged.  This might not sound like much, but since the HTML5 Canvas does not contain any DOM objects, we had to achieve the effect with our own custom code.  Here is how we did it:

 

  • First, in JavaScript we listen for Canvas “mousemove” event:

[cc lang="javascript"]
theCanvas.addEventListener("mousemove",onMouseMove, false)
[/cc]

 

  • Next we test to see if the mouse if over any of the bulbs.  We keep all bulbs in single array named clickBlocks to make this easy.
[cc lang="javascript"']
function onMouseMove(event) {
		var mouseX;
		var mouseY;

		if ( event.layerX ||  event.layerX == 0) { // Firefox
			mouseX = event.layerX ;
			mouseY = event.layerY;
		} else if (event.offsetX || event.offsetX == 0) { // Opera
			mouseX = event.offsetX;
			mouseY = event.offsetY;
		}
		for (var i =0; i < blocks.length; i++) {

			if (blocks[i].dragging) {
				blocks[i].x = mouseX - BLOCK_WIDTH/2;
				blocks[i].y = mouseY - BLOCK_HEIGHT/2;

			}
		}

		var cursor ="default";
		for (i=0; i< blocks.length; i++) {
			var tp = blocks[i];
			if ( (mouseY >= tp.y) && (mouseY <= tp.y+tp.height) && (mouseX >= tp.x) && (mouseX <= tp.x+tp.width) ) {
				cursor = "pointer";
			}
		}
		theCanvas.setAttribute("style", "cursor:" + cursor);

		for (i=0; i< clickBlocks.length; i++) {
			var tp = clickBlocks[i];
			if ( (mouseY >= tp.y) && (mouseY <= tp.y+tp.height) && (mouseX >= tp.x) && (mouseX <= tp.x+tp.width) ) {
				cursor = "pointer";
			}
		}
		theCanvas.setAttribute("style", "cursor:" + cursor);
	}
[/cc]
  • The key lines in that code, change the cursor depending on what the  mouse is over using CSS

[cc lang="javascript"]

theCanvas.setAttribute("style", "cursor: pointer”);

[/cc]

or

[cc lang="javascript"]

theCanvas.setAttribute("style", "cursor:default" );

[/cc]

Don't forget, you can join our new HTML5 Game Development forums and talk about this kind of stuff all day long!

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.

This site is protected by Comment SPAM Wiper.