Introduction to jCanvas: jQuery Meets HTML5 Canvas

Share this article

HTML5 lets you draw graphics straight into your web page using the <canvas> element and its related JavaScript API.

In this post, I’m going to introduce you to jCanvas, a free and open source jQuery-based library for the HTML5 Canvas API.

If you develop with jQuery, jCanvas makes it easier and quicker to code cool canvas drawings and interactive applications using jQuery syntax.

What is jCanvas?

The jCanvas website explains:

jCanvas is a JavaScript library, written using jQuery and for jQuery, that wraps around the HTML5 canvas API, adding new features and capabilities, many of which are customizable. Capabilities include layers, events, drag-and-drop, animation, and much more.

The result is a flexible API wrapped up in a sugary, jQuery-esque syntax that brings power and ease to the HTML5 canvas.

jCanvas enables you to do everything you can do with the native Canvas API and more. If you prefer, you can also use native HTML5 Canvas API methods with jCanvas. The draw() method serves just this purpose. Furthermore, you can easily extend jCanvas with your own methods and properties using its extend() feature.

Adding jCanvas to Your Project

To include jCanvas in your project, download the script from the official website or the GitHub page, then include it in your project folder. As mentioned, jCanvas needs jQuery to work, so be sure to include that too.

Your project’s script files will look something like this:

<script src="js/jquery.min.js></script>
<script src="js/jcanvas.min.js></script>
<script src="js/script.js></script>

The last one would be where you put your custom JavaScript using the jCanvas API. Now let’s take jCanvas for a test drive.

Setting up the HTML Document

To follow along with the examples, start by adding a <canvas> element tag to a basic HTML5 document.

<canvas id="myCanvas" width="600" height="300">
  <p>This is fallback content 
  for users of assistive technologies 
  or of browsers that don't have 
  full support for the Canvas API.</p>
</canvas>

Here are a few points of interest about the code snippet above.

  • By default, the dimensions of the <canvas> drawing surface are 300px by 150px. You can modify this default size in the width and height attributes inside the element’s markup.
  • Adding an id attribute is not required but will be an easy way to access the element with JavaScript.
  • Content inside the <canvas> element is just a bitmap image. This makes it inaccessible to users of assistive technologies. Also, browsers that don’t have support for the Canvas API will not be able to access its content or interact with it in any way. Therefore, while techniques aiming to make <canvas> more accessible are yet to be made available, adding some fallback content for this category of users is the recommended practice.

If you were to use the native Canvas API, your JavaScript would look something like this:

var canvas = document.getElementById('myCanvas'),
    context = canvas.getContext('2d');

The variable context in the code above stores a reference to the 2D context property of the Canvas object. It’s this property that enables you to access all other properties and methods exposed by the HTML5 Canvas API.

If you’d like to learn more about the topic, HTML5 Canvas Tutorial: An Introduction by Ivaylo Gerchev is a great read.

jCanvas methods and properties already contain a reference to the 2D context, therefore you can jump straight into drawing.

Drawing Shapes with jCanvas

Most jCanvas methods accept a map of property-value pairs that you can list in any order you like.

Let’s start by drawing a rectangle shape.

The Rectangle Shape

This is how you draw a rectangle shape using the drawRect() method of the jCanvas object.

// Store the canvas object into a variable
var $myCanvas = $('#myCanvas');

// rectangle shape 
$myCanvas.drawRect({
  fillStyle: 'steelblue',
  strokeStyle: 'blue',
  strokeWidth: 4,
  x: 150, y: 100,
  fromCenter: false,
  width: 200,
  height: 100
});

The snippet above caches the canvas object into a variable called $myCanvas. The properties inside the drawRect() method are mostly self-explanatory, but here’s a brief rundown:

  • fillStyle sets the rectangle’s background color;
  • strokeStyle sets its border color;
  • strokeWidth sets the shape’s border width;
  • x and y set the coordinates corresponding to the rectangle’s horizontal and vertical position inside the canvas. A value of 0 for x and of 0 for y, i.e., (0, 0), corresponds to the top left corner of the canvas. The x coordinates increase to the right and the y coordinates increase towards the bottom of the canvas. When drawing the rectangle, by default, jCanvas takes the x and y coordinates to lie at the center of the shape.
  • To change this so that x and y correspond to the rectangle’s top left corner, set the fromCenter property to false.
  • Finally, the width and height properties set the dimensions of the rectangle.

Rectangle drawn on canvas with explanation of canvas coordinates system

Here is a demo with the rectangle shape:

See the Pen jCanvas example: Rectangle by SitePoint (@SitePoint) on CodePen.

Arcs and Circles

Arcs are portions of the rim of a circle. With jCanvas, drawing arcs is just a matter of setting the desired values for a few properties inside the drawArc() method:

$myCanvas.drawArc({
  strokeStyle: 'steelblue',
  strokeStyle: 'blue',
  strokeWidth: 4,
  x: 300, y: 100,
  radius: 50,
  // start and end angles in degrees
  start: 0, end: 200
});

Drawing arcs involves setting a value for the radius property as well as the start and end angles in degrees. If you’d like the direction of your arc to be counterclockwise, add the ccw property to the code above and set it to true.

Here’s a CodePen demo of the above code:

See the Pen jCanvas example: Arc by SitePoint (@SitePoint) on CodePen.

Drawing a circle is as easy as omitting both start and end properties from the drawArc() method.

For instance, here’s how you can draw a simple graphic of a smiling face using only arc shapes:

$myCanvas.drawArc({
  // draw the face
  fillStyle: 'yellow',
  strokeStyle: '#333',
  strokeWidth: 4,
  x: 300, y: 100,
  radius: 80
}).drawArc({
  // draw the left eye
  fillStyle: '#333',
  strokeStyle: '#333',
  x: 250, y: 70,
  radius: 5
}).drawArc({
  // draw the right eye
  fillStyle: '#333',
  strokeStyle: '#333',
  x: 350, y: 70,
  radius: 5
}).drawArc({
  // draw the nose
  strokeStyle: '#333',
  strokeWidth: 4,
  ccw: true,
  x: 300, y: 100,
  radius: 30,
  start: 0,
  end: 200
}).drawArc({
  // draw the smile
  strokeStyle: '#333',
  strokeWidth: 4,
  x: 300, y: 135,
  radius: 30,
  start: 90,
  end: 280
});

Remember that jCanvas is based on the jQuery library, therefore you can chain jCanvas methods the same way you can chain jQuery methods.

Here’s how the code above renders in the browser:

See the Pen jCanvas example: Smiling Face by SitePoint (@SitePoint) on CodePen.

Drawing Lines and Paths

You can quickly draw lines with jCanvas using the drawLine() method and plotting a series of points to which your lines are going to connect.

$myCanvas.drawLine({
  strokeStyle: 'steelblue',
  strokeWidth: 10,
  rounded: true,
  closed: true,
  x1: 100, y1: 28,
  x2: 50, y2: 200,
  x3: 300, y3: 200,
  x4: 200, y4: 109
});

The code above sets the rounded and closed properties to true, thereby rounding the corners of the line and closing the traced path.

See the Pen jCanvas example: Connected lines by SitePoint (@SitePoint) on CodePen.

You can also draw flexible paths using the drawPath() method. Think of a path as one or more connected lines, arcs, curves, or vectors.

The drawPath() method accepts a map of points and a map of x and y coordinates for the sub-paths inside each point. You also need to specify the type of path you’re going to draw, e.g., line, arc, etc.

Here’s how you can draw a pair of connected horizontally and vertically pointing arrows using drawPath() and draw arrows(), the latter of which is a handy jCanvas method that enables you to quickly draw an arrow shape on the canvas:

$myCanvas.drawPath({
  strokeStyle: '#000',
  strokeWidth: 4,
  x: 10, y: 10,
  p1: {
    type: 'line',
    x1: 100, y1: 100,
    x2: 200, y2: 100
  },
  p2: {
    type: 'line',
    rounded: true,
    endArrow: true,
    arrowRadius: 25,
    arrowAngle: 90,
    x1: 200, y1: 100,
    x2: 290, y2: 100
 },
 p3: {
   type: 'line',
   rounded: true,
   endArrow: true,
   arrowRadius: 25,
   arrowAngle: 90,
   x1: 100, y1: 100,
   x2: 100, y2: 250
  }
});

The x and y coordinates of each sub-path are relative to the x and y coordinates of the entire path.

And here’s the result:

See the Pen jCanvas example: Connected Arrows by SitePoint (@SitePoint) on CodePen.

Drawing Text

You can quickly draw text on the canvas with the aptly named drawText() method. The main properties you need for this to work are:

  • text. Set this property to the text content you’d like to display on the canvas: e.g. 'Hello world'
  • fontSize. The value for this property determines the size of the text on canvas. You can set the value for this property with a number, which jCanvas interprets as a value in pixels: fontSize: 30. Alternatively, you can use points, but in such a case you need to specify the measurement inside quotes: fontSize: '30pt'
  • fontFamily allows you to specify a typeface for your text image: 'Verdana, sans-serif'.

Here’s the sample code:

$myCanvas.drawText({
  text: 'Canvas is fun',
  fontFamily: 'cursive',
  fontSize: 40,
  x: 290, y: 150,
  fillStyle: 'lightblue',
  strokeStyle: 'blue',
  strokeWidth: 1
});

And this is what it looks like inside the <canvas> element on the web page:

See the Pen jCanvas example: Drawing text by SitePoint (@SitePoint) on CodePen.

Drawing Images

You can import and manipulate images using the drawImage() method. Here’s an example:

$myCanvas.drawImage({
  source: 'imgs/cat.jpg',
  x: 250, y: 100,
  fromCenter: false,
  shadowColor: '#222',
  shadowBlur: 3,
  rotate: 40
});

And this is how the code above renders:

See the Pen jCanvas example: Importing and manipulating an image by SitePoint (@SitePoint) on CodePen.

You can view and fiddle around with all the examples above combined into a single CodePen demo here.

Canvas Layers

If you’ve ever used an image editor application like Photoshop or Gimp, you’re already familiar with layers. The cool part of working with layers is that you gain the ability to manipulate each image on your canvas individually, by drawing it on its own layer.

jCanvas offers a powerful layer API that adds flexibility to your canvas-based designs.

Here’s an overview of how to use jCanvas layers.

Adding Layers

You can only draw one object on each layer. You can add layers to your jCanvas project in either of two ways:

  • Use the addLayer() method followed by the drawLayers() method
  • Set the layer property to true inside any of the drawing methods

Here’s how you apply the first technique to draw a blue rectangle.

$myCanvas.addLayer({
  type: 'rectangle',
  fillStyle: 'steelblue',
  fromCenter: false,
  name: 'blueRectangle',
  x: 50, y: 50,
  width: 400, height: 200
}).drawLayers();

See the Pen PZeNGp by SitePoint (@SitePoint) on CodePen.

And here’s how you apply the second method to draw the same rectangle:

$myCanvas.drawRect({
  fillStyle: 'steelblue',
  layer: true,
  name: 'blueRectangle',
  fromCenter: false,
  x: 50, y: 50,
  width: 400, height: 200
});

See the Pen zrjqKb by SitePoint (@SitePoint) on CodePen.

As you can see, with each of the above, we get the same result.

The important point to notice in both code samples above is that the layer has a name that you set via the name property. This makes it easy to refer to this layer in code and do all sorts of cool things with it, like changing its index value, animating it, removing it, etc.

Let’s see how we can do this.

Animating Layers

You can quickly add animations to your layer-based drawings with jCanvas using the animateLayer() method. This method accepts the following parameters:

  • The layer’s index or name
  • An object with key-value pairs of properties to animate
  • The animation’s duration in milliseconds. This is an optional parameter, if you don’t set it, it defaults to 400
  • The easing of the animation. This is also an optional parameter, if you don’t set it, it defaults to swing
  • An optional callback function that runs when the animation completes.

Let’s see the animateLayer() method in action. We’ll draw a semi-transparent orange circle on a layer, then animate its position, color, and opacity properties:

// Draw circle
$myCanvas.drawArc({
  name: 'orangeCircle',
  layer: true,
  x: 50, y: 50,
  radius: 100,
  fillStyle: 'orange',
  opacity: 0.5
});

// Animate the circle layer 
$myCanvas.animateLayer('orangeCircle', {
  x: 150, y: 150,
  radius: 50,
}, 1000, function(layer) { // Callback function
  $(this).animateLayer(layer, {
    fillStyle: 'darkred',
    x: 250, y: 100,
    opacity: 1
  }, 'slow', 'ease-in-out');
});

Check out the demo below to see the animation:

See the Pen jCanvas example: Animating Layers by SitePoint (@SitePoint) on CodePen.

You can view all the three previous examples combined in this CodePen demo.

Draggable Layers

One more cool feature I’d like to draw your attention to is the ability to turn a regular jCanvas layer into a draggable layer by simply setting the draggable property of the layer to true.

Here’s how:

$myCanvas.drawRect({
  layer: true,
  draggable: true,
  bringToFront: true,
  name: 'blueSquare',
  fillStyle: 'steelblue',
  x: 250, y: 150,
  width: 100, height: 100,
  rotate: 80,
  shadowX: -1, shadowY: 8,
  shadowBlur: 2,
  shadowColor: 'rgba(0, 0, 0, 0.8)'
})
.drawRect({
  layer: true,
  draggable: true,
  bringToFront: true,
  name: 'redSquare',
  fillStyle: 'red',
  x: 190, y: 100,
  width: 100, height: 100,
  rotate: 130,
  shadowX: -2, shadowY: 5,
  shadowBlur: 3,
  shadowColor: 'rgba(0, 0, 0, 0.5)'
});

The snippet above draws two draggable rectangle layers by incorporating: draggable: true. Also, note the use of the bringToFront property, which ensures that when you drag a layer, it automatically gets pushed to the front of all other existing layers.

Finally, the code rotates the layers and sets a box shadow, just to show how you can quickly add these effects to your jCanvas drawings.

The result looks like this:

Example of draggable rectangle layers

If you’d like your app to do something before, during, or after moving a draggable layer, jCanvas makes it easy to accomplish this by supporting callback functions during the relevant events:

  • dragstart triggers when you start dragging the layer
  • drag fires as you drag the layer
  • dragstop triggers when you stop dragging the layer
  • dragcancel occurs when you drag the layer off the border of the drawing surface of the canvas.

Let’s say you’d like to display a message on the page after the user finishes dragging a layer. You can reuse the code snippet above by adding a callback function to the dragstop event, like so:

$myCanvas.drawRect({
  layer: true,

  // Rest of the code as shown above...

  // Callback function
  dragstop: function(layer) {
    var layerName = layer.name;
    el.innerHTML = 'The ' + layerName + ' layer has been dropped.';
  }
})
.drawRect({
  layer: true,

  // Rest of the code...

  // Callback function
  dragstop: function(layer) {
    var layerName = layer.name;
    el.innerHTML = 'The ' + layerName + ' layer has been dropped.';
  }
});

After dragging each square, you’ll see a message on the page telling you which color square you just dropped. Try it out in the demo below:

See the Pen Draggable jCanvas Layers with Callback Function by SitePoint (@SitePoint) on CodePen.

Conclusion

In this post I’ve introduced you to jCanvas, a new jQuery-based library that works with the HTML5 Canvas API. I’ve illustrated some of jCanvas methods and properties that quickly enable you to draw on the canvas surface, add visual effects, animations, and draggable layers.

There’s so much more that you can do with jCanvas. You can visit the jCanvas documentation for detailed guidance and examples, which you can quickly test in the sandbox on the jCanvas website.

To accompany this article, I’ve put together a basic painting application on CodePen using the jCanvas drawLine() method:

See the Pen jCanvas Painting App by SitePoint (@SitePoint) on CodePen.

Feel free to make it better by adding more features and sharing your results with the SitePoint community.

Frequently Asked Questions (FAQs) about jCanvas: jQuery Meets HTML5 Canvas

What is jCanvas and how does it relate to jQuery and HTML5 Canvas?

jCanvas is a powerful JavaScript library that combines the capabilities of jQuery and HTML5 Canvas to simplify the process of creating complex graphics on a web page. It leverages the simplicity and versatility of jQuery, a fast, small, and feature-rich JavaScript library, and the graphical power of HTML5 Canvas, which is an HTML element used to draw graphics on a web page. jCanvas provides a simple and consistent API for drawing shapes, creating animations, handling events, and much more.

How do I get started with jCanvas?

To get started with jCanvas, you first need to include the jQuery library and the jCanvas library in your HTML file. You can download these libraries from their respective websites or use a Content Delivery Network (CDN). Once you have included these libraries, you can start using jCanvas functions to draw on the canvas.

How can I draw shapes using jCanvas?

jCanvas provides several functions to draw shapes on the canvas. For example, you can use the drawRect() function to draw a rectangle, the drawArc() function to draw an arc, and the drawPolygon() function to draw a polygon. Each of these functions accepts a properties object that specifies the characteristics of the shape, such as its position, size, color, and so on.

Can I animate shapes with jCanvas?

Yes, jCanvas provides a powerful animation feature that allows you to animate shapes on the canvas. You can use the animate() function to animate the properties of a shape over a specified duration. This function uses the jQuery animation engine, so it supports all the easing functions provided by jQuery.

How can I handle events with jCanvas?

jCanvas provides several functions to handle events on the canvas. For example, you can use the click() function to handle click events, the mouseover() function to handle mouseover events, and the mousedown() function to handle mousedown events. Each of these functions accepts a callback function that is called when the event occurs.

Can I use jCanvas to create complex graphics?

Yes, jCanvas is designed to simplify the process of creating complex graphics on a web page. It provides a wide range of functions to draw shapes, create animations, handle events, and much more. With jCanvas, you can create anything from simple shapes to complex animations and interactive graphics.

Is jCanvas compatible with all browsers?

jCanvas is compatible with all modern browsers that support the HTML5 Canvas element. This includes the latest versions of Google Chrome, Mozilla Firefox, Apple Safari, and Microsoft Edge. However, it does not support Internet Explorer 8 or earlier, as these browsers do not support the HTML5 Canvas element.

How can I troubleshoot issues with jCanvas?

If you encounter issues with jCanvas, you can check the console for error messages, as jCanvas provides detailed error messages to help you troubleshoot issues. You can also refer to the jCanvas documentation, which provides comprehensive information about the library and its functions.

Can I use jCanvas in commercial projects?

Yes, jCanvas is released under the MIT License, which means you can use it in both personal and commercial projects for free. However, you must include the original copyright notice and disclaimer in any copy of the software or its documentation.

Where can I find more resources about jCanvas?

You can find more resources about jCanvas on its official website, which provides a comprehensive documentation, examples, and tutorials. You can also find useful information on web development websites and forums, such as Stack Overflow and SitePoint.

Maria Antonietta PernaMaria Antonietta Perna
View Author

Maria Antonietta Perna is a teacher and technical writer. She enjoys tinkering with cool CSS standards and is curious about teaching approaches to front-end code. When not coding or writing for the web, she enjoys reading philosophy books, taking long walks, and appreciating good food.

canvas apihtml5 canvasjCanvasLouisL
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week