Alex Rivera | Logout

Relatively sizing HTML Canvas

Asked 2011-08-24T02:42:10.710
17

The HTML5 <canvas> element does not accept relative sizes (percent) for its width and height properties.

What I'm trying to accomplish is to have my canvas sized relative to the window. This is what I've come up with so far, but I'm wondering if there is a better way that is:

  1. Simpler
  2. Does not require wrapping the <canvas> in a <div>.
  3. Not dependent on jQuery (I use it to get the width/height of the parent div)
  4. Ideally, doesn't redraw on browser resize (but I think that might be a requirement)

See below for the code, which draws a circle in the middle of the screen, 40% wide up to a maximum of 400px.

Live demo: http://jsbin.com/elosil/2

Code:

<!DOCTYPE html>
<html>
<head>
    <title>Canvas of relative width</title>
    <style>
        body { margin: 0; padding: 0; background-color: #ccc; }
        #relative { width: 40%; margin: 100px auto; height: 400px; border: solid 4px #999; background-color: White; }
    </style>
    <script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script>
        function draw() {
            // draw a circle in the center of the canvas
            var canvas = document.getElementById('canvas');
            var relative = document.getElementById('relative');
            canvas.width = $(relative).width();
            canvas.height = $(relative).height();
            var w = canvas.width;
            var h = canvas.height;
            var size = (w > h) ? h : w; // set the radius of the circle to be the lesser of the width or height;
            var ctx = canva
Edit
Report

1 Answer

9

Like said by sethobrien a canvas element has TWO pairs width/height of attributes.

  1. canvas.width / canvas.height are about the size in pixel of the buffer that will contains the result of drawing commands.

  2. canvas.style.width / canvas.style.height are about the size used to show the canvas object in the browser window and they can be in any of the units supported by css.

You can indeed set canvas.width and canvas.height just once, do the drawing in the canvas, setting the style size parameters in percentage and then forget about redrawing the canvas content. Of course this means that the browser will just do the scaling itself like for a regular image loaded from the network so the visible result will show pixel scaling artifacts.

You need to redraw the canvas content after the resize of the canvas element only if you want pixel-perfect results.

answered 2011-08-24T08:28:31.350

Your Answer