Resizable Canvas (JQuery UI)

Joubert Nel picture Joubert Nel · Dec 30, 2009 · Viewed 21.4k times · Source

ANY DOM element can be made resizable according to this page: http://jqueryui.com/demos/resizable/

However, it seems that this doesn't work for the CANVAS element. Possible?

Answer

Xavi picture Xavi · Jan 11, 2010

Canvas has two types of resize behavior:

  • Resizing where the contents are stretched to fit the canvas's new dimensions
  • Resizing where the contents remain static while the canvas grows or shrinks

Here's a page that demonstrates the two types of "resizing": http://xavi.co/static/so-resizable-canvas.html

If you want the first type of resizing (stretch the content) then place the canvas into a container div and set the width and height of the canvas to 100% using CSS. Here's what that code might look like:

/* The CSS */
#stretch {
    height: 100px;
    width: 200px;
}

#stretch canvas {
    width: 100%;
    height: 100%;
}

<!-- The markup -->
<div id="stretch"><canvas></canvas></div>

// The JavaScript
$("#stretch").resizable();

The second type of resizing (static content) is a two step process. First you must adjust the width and height attributes of the canvas element. Unfortunately, doing this clears the canvas, so you must then re-draw all its contents. Here's bit of code that does this:

/* The CSS */
#resize {
    height: 100px;
    width: 200px;
}

<!-- The markup -->
<div id="resize"><canvas></canvas></div>

// The JavaScript
$("#resize").resizable({ stop: function(event, ui) {
    $("canvas", this).each(function() { 
        $(this).attr({ width: ui.size.width, height: ui.size.height });

        // Adjusting the width or height attribute clears the canvas of
        // its contents, so you are forced to redraw.
        reDraw(this);
    });
} });

Currently the code above re-draws the canvas's content when the user stops resizing the widget. It's possible to re-draw the canvas on resize, however resize events occur fairly often and re-draws are expensive operations -- approach with caution.