Coder Perfect

Canvas is stretched when using CSS but normal with “width” / “height” properties


I have two canvases; one uses the HTML width and height elements to size it, while the other uses CSS:

<canvas id="compteur1" width="300" height="300" onmousedown="compteurClick(;"></canvas>
<canvas id="compteur2" style="width: 300px; height: 300px;" onmousedown="compteurClick(;"></canvas>

Compteur1 works properly, however Compteur2 does not. On a 300×300 canvas, the content is drawn using JavaScript.

Why is there a discrepancy in the display?

Asked by Sirber

Solution #1

The width and height attributes appear to define the size of the canvas’s coordinate system, but the CSS properties appear to only indicate the size of the box in which it will be displayed.

The HTML specification explains it thus way:

Answered by SamB

Solution #2

You can use to set the width and height you require.

canvasObject.setAttribute('width', '475');

Answered by fermar

Solution #3

CSS width and height rules determine the size of the canvas element that will be drawn to the page for canvas> elements. The width and height HTML attributes, on the other hand, define the size of the canvas API’s coordinate system or ‘grid.’

Consider the following (jsfiddle):

Both have the same thing drawn on them in terms of the canvas element’s internal coordinates. However, because the canvas as a whole is stretched across a larger area by the CSS rules in the second canvas, the red rectangle will be twice as broad.

Note: If the width and/or height CSS rules aren’t supplied, the browser will size the element using the HTML attributes, with 1 unit of these values equaling 1px on the page. If these parameters aren’t given, a width of 300 pixels and a height of 150 pixels will be used by default.

Answered by Ben Jackson

Solution #4

If you set the width and height in CSS, the canvas will be stretched. If you want to alter the canvas’s dimensions dynamically, use JavaScript as follows:

canvas = document.getElementById('canv');
canvas.setAttribute('width', '438');
canvas.setAttribute('height', '462');

Answered by Bluerain

Solution #5

The canvas element scales based on the canvas width and height, while the browser uses the css width and height. Read the css width and height in javascript and set the canvas width and height to those values.

var myCanvas = $('#TheMainCanvas');
myCanvas[0].width = myCanvas.width();
myCanvas[0].height = myCanvas.height();

Answered by Russell Harkins

Post is based on