Reputation: 462
I have simplified my issue to a basic HTML document with a <canvas>
element:
body {
border: 1px solid #ff5500;
background-color: black;
}
canvas {
width: 100%;
height: 100%;
}
<canvas id="canv" style='width:1024px;height:768px'></canvas>
But however I set the width
and height
(using pixels, percentages or viewport units), whether or not I set the style (e.g. style='width:1024px;height:768px'
), and however I resize the browser window, the dev console always reports width x height as 300x150. Why is this, and how do I deal with it?
Here's the output from the dev console:
var c = document.getElementById("canv");
undefined
c.style.width
"1024px"
c.style.height
"768px"
c.width
300
c.height
150
The same behaviour occurs in both Chromium and Firefox.
I have trawled Stack Overflow and the web in general and found much on the difference between width
and clientWidth
, and a similar question regarding Fabric.js, but no answer to this specific question.
Upvotes: 7
Views: 3494
Reputation: 2882
This link gives a decent explanation. Essentially, you need to set the width
and height
of the DOM element as the product of its CSS size and the device's pixel ratio. Then set the scale
of the context you create. I've copied the code in case the link dies.
const width = 300;
const height = 150;
const pixelRatio = window.devicePixelRatio;
const can2 = document.getElementById('canvas2');
can2.width = width * pixelRatio;
can2.height = height * pixelRatio;
can2.style.width = width + 'px';
can2.style.height = height + 'px';
const ctx2 = can2.getContext('2d');
ctx2.scale(pixelRatio, pixelRatio);
Upvotes: 1
Reputation: 577
You have to change canv.width or .height in JS or set the attribute in HTML directly. Without any CSS or JS needed.
Example:
var can = document.querySelector("#testC");
var can2 = document.querySelector("#testC2");
console.log("Canvas before JS: ", can.width, "x", can.height);
console.log("Canvas in HMTL: ", can2.width, "x", can2.height);
can.width = 600;
can.height = 600;
console.log("Canvas after JS: ", can.width, "x", can.height);
console.log("Canvas in HMTL: ", can2.width, "x", can2.height);
<canvas id="testC" width="300" height="300">
<canvas id="testC2" width="600" height="600">
This will log:
Canvas before JS: 300x300
Canvas in HMTL: 600x600
Canvas after JS: 600x600
Canvas in HMTL: 600x600
Upvotes: 5
Reputation: 6160
I think the width and height that you are referring to-- are html attributes and not css.
They can be modified like this;
<canvas width="1024" height="768" style="border:1px solid black;">
</canvas>
Upvotes: 7