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(this.id);"></canvas> <canvas id="compteur2" style="width: 300px; height: 300px;" onmousedown="compteurClick(this.id);"></canvas>
Why is there a discrepancy in the display?
Asked by Sirber
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
You can use to set the width and height you require.
Answered by fermar
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
canvas = document.getElementById('canv'); canvas.setAttribute('width', '438'); canvas.setAttribute('height', '462');
Answered by Bluerain
var myCanvas = $('#TheMainCanvas'); myCanvas.width = myCanvas.width(); myCanvas.height = myCanvas.height();
Answered by Russell Harkins
Post is based on https://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-but-normal-with-width-height-properties