I\'m implementing a color picker. There is problem with the rendering. When I call c.fillRect(0, 0, 100, 80);
the size of that rectangle is 103x42 px instead of 100
The first thing to know is that a canvas
element has intrinsic dimensions = number of pixels in the inside coordinate space (set by the width
and height
attributes and properties). It also has extrinsic dimensions (style.width
and style.height
) which is the number of pixels that the image takes within the webpage. The intrinsic pixels are scaled to fit the extrinsic space.
It's confusing because an img
also has intrinsic and extrinsic dimensions, but the names of the properties are completely different from canvas
. If you set width
and height
on an image, it's basically the same as setting style.width
or style.height
; they both set the extrinsic dimensions to scale the image within the page. Meanwhile, you can only get the intrinsic dimensions of an img
using the new naturalWidth
and naturalHeight
(HTML5 browsers only) properties.
If the extrinsic dimensions are not set on both img
and canvas
, the image will be laid out at the same size as the intrinsic dimensions (i.e., scale factor would be 1).
Now, when you use jQuery, $(canvas).width('310px')
is the same as $(canvas).css('310px')
, which sets the extrinsic dimensions. You have to call $(canvas).prop('width', 310)
or simply set canvas.width = 310
to set the intrinsic width.