This recipe how to resize the HTML5 canvas dynamically when the size of the browser window changes. Weirdly, the HTML canvas element defaults to a fixed 300 pixels wide by 150 pixels high, and that won’t change for compatibility reasons. It’s right there in the W3C spec at http://www.w3.org/TR/2012/WD-html5-author-20120329/the-canvas-element.html#the-canvas-element.

Complete HTML Code for Resizing the Canvas Dynamically

You came here for the code, so here it is. Click here to see it in action (http://htmlcheats.com/wp-content/uploads/2013/06/resizecanvas.html), though it doesn’t look like much. The canvas is stretched to fit the browser window and a blue border displays around the edge; resize the browser window to see.  An explanation follows.

 

How it Works

The key is to register an event listener, which is a way to respond to changes in the DOM. There are many possible events one can listen to. In this case it’s one that fires when the window resizes. The event listener calls a method of your choice, in this case, one to resize the canvas and to draw a border around it. There are also a few practical issues regarding  program initialization and HTML styling. We’ll cover those briefly too.

<style> issues: overflow and display

The <style> section is pretty self-explanatory but two parts bear explanation. overflow: hidden is required because otherwise scrollbars would display. Sometimes they’re useful but for this example they only get in the way. display: block makes the canvas act like a <div> as opposed to a <span>. That is, it ensures nothing displays on either size of the canvas.

<canvas> naming and getElementById()

To draw on an HTML page you need a <canvas> tag somewhere between the <body> and </body> tags. You need to give it an ID in quotes, and that ID will be used by the getElementById() DOM method so make sure the two match up.   Normally an ID should contain one or more characters, but no spaces. The ID should be unique on the page; no other element should use it.

Add a document ready function

If you’re new to Javascript and DOM programming this construct may look odd:

It is an anonymous (unnamed) function that executes once, and theoretically only when the HTML page has been fully loaded. An HTML page is a complex and wonderful thing. It has headings and paragraphs of text, which must be loaded into the DOM. It may images or other media files, which must also go there.

It may also have Javascript that manipulates the DOM. However, the HTML specification doesn’t promise that assets will be loaded  in the order they appear on the page. It’s possible that Javascript will load earlier than some other assets, and try to manipulate elements on the page that are not yet recognize by the DOM.

So before using Javascript on the DOM, you need what is traditionally called a document ready function. Due to the nature of the HTML spec, variations in browsers, and the asynchronous nature of the loading of web page elements, determining whether the document is ready takes far more than a line of code or two.

The “theoretically” part mentioned above is that you have no assurance in this example that the document has been loaded. Here it doesn’t matter because the file is so small. However, any real-life HTML app using Javascript will have something very much like that anonymous function designed to run.

The most common document ready function looks almost exactly like the example above. It’s from JQuery:

If you’re wondering what document ready code that doesn’t require JQuery looks like, Stackoverflow takes on the issue at http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery. Reading it gave me an anxiety attack. In production code, I’d strongly recommend you stick to JQuery or something like it to determine document readiness.

Get the canvas from the DOM and obtain its graphic context

To draw on the canvas, you must get access to the DOM by declaring a Javascript variable (htmlCanvas, in this case) and call the DOM’s getElementById method, passing the ID of the canvas tag to it.

Then, you need to get its graphics context, a reference to the drawing surface itself. Use the getContext('2d') method call for that. Yes, there’s a 3D context too. It’s called ‘webgl’ but isn’t germaine to this task.

Start responding to window resize events

The goal is to redraw the canvas when the browser window dimensions change. That’s the event listener. In this example the user-defined function resizeCanvas() is called each time the browser’s resize event is triggered.

Connecting the event to the resizeCanvas() method only needs to happen once. It’s placed in the intialize() function along with resizeCanvas() because the resize event doesn’t get fired on window creation.

Resize canvas based on window dimensions

Remember that while Javascript is a complete, general-purpose language, it runs in the context of the browser’s window object. You are no doubt very familiar with the best-known method of the window object, which is alert(). Two properties of the window object are its current width and height, innerWidth and innerHeight. These are used to draw the canvas at maximum size when the window object’s dimensions change:

Redraw canvas after it’s been resized

The redraw() function gets called from the resizeCanvas() event. In production code this would be more interesting than drawing a bordered canvas. In a graphics editor, for example, it would redraw the image and perhaps a toolbar.

Summary

This skeleton is everything you need for an app that needs a resizable canvas. It:

  • Adds HTML markup for a canvas element with a unique ID (‘c’ in this example)
  • Declares a Javascript variable named htmlCanvas with a reference to that canvas’s ID using the DOM’s getElementById() method
  • Gets a graphics context to draw on (the variable named context)
  • Calls a user-defined function called initialize() in this example that gets access to the browser’s resize event
  • Which creates an implicit loop, calling the user-defined resizeCanvas() method when the browser window changes size
  • As long as the page is active the context remains available for graphics operations

 

 

Fabric.js (http://fabricjs.com/) is a feature-rich Javascript library for creating interactive graphics for the HTML5 Canvas with extensive, well-written tutorials (http://fabricjs.com/articles/) with a glaring shortcoming. They start in the middle–leaving high and dry the intermediate Javascript/HTML programmer who wants a short but complete “hello, world” program as a starting point and who doesn’t immediately grok the

This article hopes to bridge the gap so that you can write short HTML programs testing out Fabric.js based on those tutorials and try out the myriad services it provides. You should enjoy this. Javascript graphics libraries are fun to play with and Fabric.js in particular is a well-designed joy.

In three  lines of Javascript plus an HTML <canvas> tag you can create a graphic or text objects that can be resized, rotated, and moved. With a few more lines you can create graphics primitives with simple animations, graphic objects that can be grouped, and event listeners that respond to events such as mouse clicks.

This program you write will contain just 3 lines of Javascript and will do much more than this:

fabric.js tutorial 2013 addtext

When you run it, you’ll be able to select the text:

fabric.js tutorial 2013 text resize

 

Move it:

fabric.js tutorial 2013 text move

Resize it:

fabric.js tutorial 2013 text resized

And even rotate it:

fabric.js tutorial 2013 text rotate

 

All with 3, count ’em, 3, lines of Javascript. Click here to try it yourself.

Get to the Good Part First: The

Full HTML and Javascript For Your First Fabric.js Program

Here’s all the HTML you need to try out Fabric.js:

Part 2 of this tutorial shows you how to put together your own Fabric.js app by explaining each section of this example code.

Update June 25

Moved script tag to bottom of page