Archive for June, 2012

June 18, 2012

A simple drawing grid with HTML5 part 4

This week, we will complete the simple drawing grid by adding support for mobile browsers. Support for mobile browsers consists of enabling interaction with the canvas with touch events rather than the mouse events that are currently used.
The first step however is to add some detection for whether or not the client is using a mobile device. There really isn’t a standard way to accomplish this that I am aware of, but we can use a bit of javascript to do the job.

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i) ? true : false;
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    Any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
};

This is not a comprehensive detection of all mobile devices, but should cover the most popular ones.

Once we determine if the client is using a mobile browser, we can choose wheter or not to bind mouse events or touch events. This is a simple matter of adding an if condition when the page has been loaded.

if (!isMobile.Any()) {
	alert('not mobile');
	$("#grid").mousedown(function(e) {
		mouseDown = true;
	}).bind('mouseup', function() {
		mouseDown = false;
	}).bind('mouseleave', function() {
		mouseDown = false;
	});
	
	$("#grid").mousemove(function(e) {
		if (mouseDown) {
			drawOnCanvas(e);
		}
	});
} else {
	grid_canvas.addEventListener('touchstart', function(e) {
		mouseDown = true;
	});
	
	grid_canvas.addEventListener('touchend', function(e) {
		mouseDown = false;
	});
	
	grid_canvas.addEventListener('touchmove', function(e) {
		e.preventDefault();
		if (mouseDown) {
			drawOnCanvas(e);
		}
	});
}

You should note that by default, some mobile browsers have the default behavior for ‘ touchmove’ already defined to move the entire browser window. We can disable this by adding the following to the ‘touchmove’ event that is bound to the canvas.

e.preventDefault();

Now that we have detection and handling for mobile browsers, the drawing grid is supported in both mobile and non-mobile web browsers. As an exercise, you may choose to increase the size of the canvas and controls to make it more visible for mobile devices with smaller screens.

The entire source for our completed drawing grid application can be seen by viewing the source of the demo.

Advertisement
June 14, 2012

A simple drawing grid with HTML5 part 3

This is a continuation of our simple drawing grid series. Last week, we ended up with a functional drawing grid with a few expected controls like setting pen size and pen color. While it was functional, it left a lot to be desired from a presentation standpoint. This week, we will work on giving our application a little bit of style with css.
First, we will want to arrange the HTML a bit to support our controls being rendered to the right of the grid rather than below. This could be done with css, but for the purpose of simplicity, we will do it with a good old fashioned table.

<table>
	<tr>
		<td rowspan="2">
			<div id="container">
				<canvas id="grid">
					<p>Your browser does not support HTML5 canvas</p>
				</canvas>
			</div>
			<script type="text/javascript" src="scripts/grid.js"></script>
		</td>
		<td>
			<!-- controls -->
		</td>
	</tr>
</table> 

Instead of using buttons, to improve the appearance, we will use images for some of the controls. For the pen size selection, I chose to use text. For this, you can simply open up your favorite image editor (I chose gimp), select your preferred font, type in your label and save the image. For the other controls, you can simply use google to find images available for free via the creative commons license.
Once you have selected the images, all that is required is to change the input type of the elements from button to image and add a source path. I’ve created an images folder for this purpose, but you can place them anywhere that you choose.

<div><input type="image" src="images/eraser.png" title="erase" onclick="setEraser()" ></div>

If you remember from last week, we were using the mousedown event on any button other than mouse button one to provide the eraser functionality. To make it more intuitive, a control has been added to provide that functionality instead.
The process of choosing colors by defining a button or image input per color as we did last week isn’t very scalable. To solve this problem, we will add a color selector to the the controls section. We’ll discuss the implementation a bit later, but will define the element while working with the html.

<input type="color" id="colorpicker" name="colorpicker" /> 

Now that we have all of the controls defined, the html table should look similar to the following.

<td rowspan="2">
	<div id="container">
		<canvas id="grid">
			<p>Your browser does not support HTML5 canvas</p>
		</canvas>
	</div>
	<script type="text/javascript" src="scripts/grid.js"></script>
</td>
<td>
	<div><input type="image" src="images/smallPen.png" title="small pen" onclick="setPenSize(2)" ></div>
	<div><input type="image" src="images/mediumPen.png" title="medium pen" onclick="setPenSize(4)" ></div>
	<div><input type="image" src="images/largePen.png" title="large pen" onclick="setPenSize(8)" ></div>
	<div><input type="image" src="images/eraser.png" title="erase" onclick="setEraser()" ></div>
	<div><input type="image" src="images/trash.png" title="clear" onclick="initCanvas()" ></div>
	<input type="color" id="colorpicker" name="colorpicker" />
</td> 

Last week, our canvas used a blue background color so that it was clearly visible on the page. To improve the appearance, we will use a white background and use css to define a border. To do this, create a folder called css and an empty text file within it named grid.css. Then simply use the following to create a nice border around the canvas

#container {
	width: 400px; margin: 0px 12px 24px 12px;		
	box-shadow: 0px 5px 25px #343434;
	-moz-box-shadow: 0px 5px 25px #343434;
	-webkit-box-shadow: 0px 5px 25px #343434;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px; 
	border-radius: 10px;
}

Next, add a reference to the css script in the head section of the page.

<link rel="stylesheet" href="css/grid.css" type="text/css">

The last step is to implement the color picker functionality. Rather than re-inventing this functionality, we will use the fantastic color picker called Spectrum from Brian Gridstead. After evaluating several freely available color picker controls, Spectrum proved to be far and away the easiest to implement, most compatible with all of the major browsers, and feature complete.
The first step in implementing Spectrum is to download spectrum.js and spectrum.css. I’ve placed them in the scripts folder and the css folder respectively. Once the files are in place, add them to the page.

<script src="scripts/spectrum.js" type="text/javascript"></script>
<link rel='stylesheet' href='css/spectrum.css' type="text/css">	

And finally, bind the extension to the “colorpicker” element that we defined earlier while creating the controls section. To do this, simply add the following to grid.js .ready function.

$("#colorpicker").spectrum({
	color: "#0000ff",
	change: function(color) {
		penColor = color.toHexString();
	},
	show: function(color) {
		erase = false;
	}
});

As you can see, the change event of the color picker sets our pen color and the show event disables the erase functionality. Be sure to spend some time reviewing the excellent documentation provided on the Spectrum website to learn more about all of the options available with the extension.
For now, we have completed our face lift for the drawing application. The full source code is available via the demo.

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.

Tags: ,