Sketching with HTML5 Canvas and “Brush Images”
Posted: January 4th, 2012 | Author: Andrew | Filed under: Development, HTML5, Mobile | Tags: canvas, development, HTML5, JavaScript | 11 Comments »In a previous post on capturing user signatures in mobile applications, I explored how you capture user input from mouse or touch events and visualize that in a HTML5 Canvas. Inspired by activities with my daughter, I decided to take this signature capture component and make it a bit more fun & exciting. My daughter and I often draw and sketch together… whether its a magnetic sketching toy, doodling on the iPad, or using a crayon and a placemat at a local pizza joint, there is always something to draw. (Note: I never said I was actually good at drawing.)

Olivia & the iPad
You can take that exact same signature capture example, make the canvas bigger, and then combine it with a tablet and a stylus, and you’ve got a decent sketching application. However, after doodling a bit you will quickly notice that your sketches leave something to be desired. When you are drawing on a canvas using moveTo(x,y) and lineTo(x,y), you are somewhat limited in what you can do. You have lines which can have consisten thickness, color, and opacity. You can adjust these, however in the end, they are only lines.
If you switch your approach away from moveTo and lineTo, then things can get interesting with a minimal amount of changes. You can use images to create “brushes” for drawing strokes in a HTML5 canvas element and add a lot of style and depth to your sketched content. This is an approach that I’ve adapted to JavaScript from some OpenGL drawing applications that I’ve worked on in the past. Take a look at the video below to get an idea what I mean.
Examining the sketches side by side, it is easy to see the difference that this makes. The variances in stroke thickness, opacity & angle add depth and style, and provide the appearance of drawing with a magic marker.
It’s hard to see the subtleties in this image, so feel free to try out the apps on your own using an iPad or in a HTML5 Canvas-capable browser:
Just click/touch and drag in the gray rectangle area to start drawing.
Now, let’s examine how it all works. Both approaches use basic drawing techniques within the HTML5 Canvas element. If you aren’t familiar with the HTML5 Canvas, you can quickly get up to speed from the tutorials from Mozilla.
moveTo, lineTo
The first technique uses the canvas’s drawing context moveTo(x,y) and lineTo(x,y) to draw line segments that correspond to the mouse/touch coordinates. Think of this as playing “connect the dots” and drawing a solid line between two points.
The code for this approach will look something like the following:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(a.x, a.y);
context.lineTo(b.x, b.y);
context.lineTo(c.x, c.y);
context.closePath();
context.stroke();
The sample output will be a line from point A, to point B, to point C:

lineTo(x,y) Stroke Sample
Brush Images
The technique for using brush images is identical in concept to the previous example – you are drawing a line from point A to point B. However, rather than using the built-in drawing APIs, you are programmatically repeating an image (the brush) from point A to point B.
First, take a look at the brush image shown below at 400% of the actual scale. It is a simple image that is a diagonal shape that is thicker and more opaque on the left side. By itself, this will just be a mark on the canvas.
When you repeat this image from point A to point B, you will get a “solid” line. However the opacity and thickness will vary depending upon the angle of the stroke. Take a look at the sample below (approximated, and zoomed).

Brush Stroke Sample (simulated)
The question is… how do you actually do this in JavaScript code?
First, create an Image instance to be used as the brush source.
brush = new Image(); brush.src = 'assets/brush2.png';
Once the image is loaded, the image can be drawn into the canvas’ context using the drawImage() function. The trick here is that you will need to use some trigonometry to determine how to repeat the image. In this case, you can calculate the angle and distance from the start point to the end point. Then, repeat the image based on that distance and angle.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var halfBrushW = brush.width/2;
var halfBrushH = brush.height/2;
var start = { x:0, y:0 };
var end = { x:200, y:200 };
var distance = parseInt( Trig.distanceBetween2Points( start, end ) );
var angle = Trig.angleBetween2Points( start, end );
var x,y;
for ( var z=0; (z<=distance || z==0); z++ ) {
x = start.x + (Math.sin(angle) * z) - halfBrushW;
y = start.y + (Math.cos(angle) * z) - halfBrushH;
context.drawImage(this.brush, x, y);
}
For the trigonometry functions, I have a simple utility class to calculate the distance between two points, and the angle between two points. This is all based upon the good old Pythagorean theorem.
var Trig = {
distanceBetween2Points: function ( point1, point2 ) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
return Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) );
},
angleBetween2Points: function ( point1, point2 ) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
return Math.atan2( dx, dy );
}
}
The full source for both of these examples is available on github at:
This example uses the twitter bootstrap UI framework, jQuery, and Modernizr. Both the lineTo.html and brush.html apps use the exact same code, which just uses a separate rendering function based upon the use case. Feel free to try out the apps on your own using an iPad or in a HTML5 Canvas-capable browser:
Just click/touch and drag in the gray rectangle area to start drawing.





[...] (typeof(addthis_share) == "undefined"){ addthis_share = [];}After spending some time playing around sketching with the HTML5 canvas element earlier this week, I figured “why not add some ‘enterprise’ concepts to this [...]
Hmmmm… really interesting! I’m thinking of using it for flash… how is the performance of both methods compared?
I haven’t compared performance in HTML vs Flash, but it should definitely work. On desktop, I’m sure it will work just fine. You may have to experiment with mobile devices. Older devices might have performance issues.
[...] [...]
Hi Andrew,
I am doing on my final year project(fyp) and chance upon your post regarding this canvas drawing which is great help to my fyp. I have implemented your source code into my project. However, I am facing some problems which I hope you can give me a hand with this..
Currently i am able to draw on the canvas, but is there any way that i can implement on your codes to check if the user has drawn (from left to right) to the maximum of the canvas?
Appreciate your help and hope to receive your reply soon.. Thanks very much..
Don’t know how I got here but your article is really awesome.
You got yourself a new subscriber!
if I want to change the color brush what can i do?
Currently, there are no color filters… you would have to change the source image to change the brush color.
Hi Andrew,
I’ve been playing w/ this code and it works great! I’m planning to adopt it for use on my site, and link to you for attribution and credit. I couldn’t find any license, so please let me know if this is a problem or if you’d like attribution in any other way.
Thanks!
Reed, Feel free to use this code. If you don’t mind sharing, I’d like to see what you have built with it, whenever your application is online. The canvas sketching code code is available for use under the MIT license:
Thanks Andrew! I’m using it for this game: http://drawception.com
I just switched over to your code a few days ago and it’s working much better than what I had before.
If you’d like to check it out w/o having to play or sign up, here’s the sandbox version: http://drawception.com/sandbox/