DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Languages
  4. Sketching with HTML5 Canvas and “Brush Images”

Sketching with HTML5 Canvas and “Brush Images”

Andrew Trice user avatar by
Andrew Trice
·
Mar. 04, 12 · Interview
Like (0)
Save
Tweet
Share
14.92K Views

Join the DZone community and get the full member experience.

Join For Free

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.)




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:

  • Simple Sketch Using lineTo
  • Stylistic Sketches Using a Brush


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();






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).


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:

  • https://github.com/triceam/HTML5-Canvas-Brush-Sketch


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:

  • Simple Sketch Using lineTo
  • Stylistic Sketches Using a Brush


Just click/touch and drag in the gray rectangle area to start drawing.


 

HTML

Published at DZone with permission of Andrew Trice, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Fixing Bottlenecks in Your Microservices App Flows
  • Practical Example of Using CSS Layer
  • Mission-Critical Cloud Modernization: Managing Coexistence With One-Way Data Sync
  • Automated Testing With Jasmine Framework and Selenium

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: