23

I thought for a bit of fun I would have a look at the canvas. It seemed fairly easy to draw a box so I pretty much copied an example from the mozilla developer site. You can see it here: http://jsfiddle.net/Wolfy87/DZBwp/

As you can see it has distorted. Does anyone have any ideas? I am setting the same x/y and the same width/height. It should be a box, right?

Olical
  • 39,703
  • 12
  • 54
  • 77

3 Answers3

27

Fixed it myself, I had to set the width and height via the tag, not CSS. Lucky guess.

<canvas width='400' height='300'></canvas>
Olical
  • 39,703
  • 12
  • 54
  • 77
  • 6
    Thanks a lot. I'm having the exact problem and could not figured out why for hours. – jagttt Sep 17 '11 at 04:39
  • I just banged my head against the wall about this and figured it out. I believe the tag's properties set the interior coordinate system while the css rules set the external look and feel. – DrDisc Feb 24 '16 at 15:34
8

Canvas works like an image tag

A canvas works like an image, it has a width and a height.

In the case of an image, the browser can work out the width and height by inspecting the file. In the case of a canvas, the width and height cannot be inferred so you must set them directly as attributes.

<canvas width="400" height="400" />

CSS

When you set the width using CSS, the height will be adjusted too to maintain the aspect ratio, just like an image. You could set the width to be 100%, and the canvas will fill the container.

canvas { 
  width:100% 
}

If you set both the width and height the canvas will be stretched to fit the space you have allocated, just like an image.

Defaults

The default width and height of a canvas are 300x150, a 2/1 ratio.

superluminary
  • 47,086
  • 25
  • 151
  • 148
0

I had the same problem, but I was able to solve it, and include the height and width tags in my css, but I could not used the 'px' unit or '%' on the height or width.

canvas#my-id{
    width:400;
    height:300;
}

Whether you use the html tag, css or set it with javascript/jquery etc shouldn't be matter.

ramsey0
  • 1,587
  • 1
  • 12
  • 10
  • A more comprehensive answer can be found here: http://stackoverflow.com/questions/5034529/size-of-html5-canvas-via-css-versus-element-attributes – ramsey0 Apr 01 '14 at 13:13