Archive for June 5th, 2012

June 5, 2012

A simple drawing grid with HTML5 part 2

Last week we created a full page drawing surface with HTML5 canvas. This week we will add a few simple controls to allow for the user to clear the surface, set drawing colors, and choose different sizes for the ‘pen’. Next week, we will finish the simple drawing application with a bit of css styling.
To make room for some controls, the drawing surface will no longer encompass the entire page. Instead of a fixed width, we will still scale the size by a factor of one half x and y.

var viewWidth = window.innerWidth * 0.5;
var viewHeight = window.innerHeight * 0.5;

If you remember last week, we relied on window events for clearing and initializing the canvas. Since we will be adding a button for clearing the canvas, the window events are no longer required. Instead, we will initialize the canvas when the page has been loaded.

$(document).ready(function() {
	
	initCanvas();

	$("#grid").mousedown(function(e) {
		mouseDown = true;
		mouseButton = e.which;
	}).bind('mouseup', function() {
		mouseDown = false;
	}).bind('mouseleave', function() {
		mouseDown = false;
	});
	
	$("#grid").mousemove(function(e) {
		if (mouseDown) {
			var x = Math.floor((e.pageX-xOffset) / penWeight);
			var y = Math.floor((e.pageY-yOffset) / penWeight);
			if (x != lastX || y != lastY) {
				lastX = x;
				lastY = y;
				ctx.fillStyle = mouseButton == 1 ? penColor : backgroundColor;
				ctx.fillRect(x*penWeight, y*penWeight, penWeight, penWeight);
			}
		}
	});
});

The one important change to this scripting is that we have added a bind for the ‘mouseleave’ event. This is required since the canvas no longer covers the entire page.
The canvas initialization scripting should be separated as it also provides the functionality of clearing the canvas by clicking on a button.

<input type="button" value="Clear" onclick="initCanvas()" >
initCanvas = function() {
    grid_canvas.setAttribute("width", viewWidth);
    grid_canvas.setAttribute("height", viewHeight);
    grid_canvas.style.top = 0;
    grid_canvas.style.left = 0;
	
	ctx.clearRect(0,0,viewWidth,viewHeight);
	ctx.fillStyle = backgroundColor;
	ctx.fillRect(0,0,viewWidth,viewHeight);	
};

Similarly, some buttons will be added to allow the user to specify the drawing color and drawing size.

<input type="button" value="Red Pen" onclick="setPenColor('rgb(255,0,0)')" >
<input type="button" value="Small Pen" onclick="setPenSize(2)" >
setPenColor = function(rgb) {
	penColor = rgb;
};

setPenSize = function(size) {
	penWeight = size;
}

So now we have a more useful drawing application that gives that provides some expected functionality. The results will still be fairly primitive, but we will work on improving the presentation next week with some css styling.

The complete source can be found by viewing the source of the demo.

Advertisement
Tags: ,