Nasser Al-Shawwa
Nasser Al-Shawwa

Reputation: 3653

Incorrect sizing of canvas context

I have two canvas blocks, one sized with inline attributes, and the other sized with CSS.

HTML:

<canvas id="canv_in" width="400" height="400"> </canvas>
<canvas id="canv_ss"> </canvas>

CSS:

canvas {
     background-color : rgba(200, 200, 200, 0.5);
}

#canv_ss {
    width : 400px;
    height: 400px;        
}

The canvases both have the same dimensions, but when I try to draw the same rectangle in both of them, I get a different result. Here's the js:

var canvasElems = document.getElementsByTagName("canvas");
var canvasContext;

for(i = 0; i < canvasElems.length; ++i) {
    canvasContext = canvasElems[i].getContext("2d");
    canvasContext.fillStyle = "rgba(0, 0, 225, 1.0)";
    canvasContext.fillRect(120, 10, 150, 150);
}

Here's the result:

Canvas is weird

So, my question is: how do we size the rectangle as intended, while keeping my element styles in CSS? Is that not possible? Why is the rectangle on the right behaving strangely?

Upvotes: 0

Views: 618

Answers (1)

4dgaurav
4dgaurav

Reputation: 11506

The width attribute defaults to 300px and the height to 150px. Adding a stylesheet to the element merely scales the box to that size and does not extend the coordinate space.

A canvas element can be sized arbitrarily by a style sheet, its bitmap is then subject to the 'object-fit' CSS property.

The intrinsic dimensions of the canvas element when it represents embedded content are equal to the dimensions of the element's bitmap.

The HTML attributes (width and height) sets the canvas dimensions, which determines how objects are measured on the canvas.

The CSS style sets the canvas display size, which determines dimensions of canvas on browser. If the display size is different from the dimensions, the canvas will be stretched when drawn.

When a canvas element represents embedded content, it provides a paint source whose width is the element's intrinsic width, whose height is the element's intrinsic height, and whose appearance is the element's bitmap.

Whenever the width and height content attributes are set, removed, changed, or redundantly set to the value they already have, if the canvas context mode is direct-2d, the user agent must set bitmap dimensions to the numeric values of the width and height content attributes.

The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.

Conclusion

There is a difference between the canvas dimensions and the canvas display size.

If you only define the dimensions, that will also be used as the display size, i.e. the canvas is drawn at scale 1:1.

If you only define the display size, the dimensions will get the default value 300 times 150.

You have more information here.

Upvotes: 1

Related Questions