Search code examples
htmlcanvasscale

HTML Canvas scale


I've started experimenting with drawing on a Canvas object. In the past my exposure to a Canvas has been centered (NPI) around image manipulation, so I'm moderately familiar with its coordinate system and transformation process. I'm working with a test canvas that has a screen dimension of 30 X 30. After getting a handle to the 2D context I issue one call:

ctx.fillRect(0,0,10,10);

produces a little black spec about the size of a pin head in the upper left corner. To get the rectangle to be of any size, say something approximate 1/4 of the canvas, requires an adjustment to:

ctx.fillRect(0,0,200,200);

So, how has this canvas's scale been skewed? Yes, I guess I could "de-scale" it back to something resembling normal, but I'd like to figure out what's causing this in the first place. I've disabled Jquery thinking it might be interfering somehow, but that did not help.

Any ideas?

UPDATE:

The canvas is added to the dom along these lines:

<canvas id='foo_" + self.groupIndex + "' class='hCanvasClassName'>"

whereby the CSS defines the width at 100% and the height is assigned by JS code.


Solution

  • You didn't show the code for this, but it sounds as you have applied the size for the canvas using CSS and not directly on the element which would explain why it scales down.

    You need to do this:

    <canvas width="30" height="30" id="myCanvas"></canvas>
    

    If you did this:

    <canvas style="width:30px;height;30px;" id="myCanvas"></canvas>
    

    what will happen is that the canvas element uses a default size (300x150, see here: http://jsfiddle.net/AbdiasSoftware/CfMNf/) and then you scale that down to 30x30 by css which means everything now drawn to the canvas will be scaled accordingly.