How can i get the width and height of the canvas element in JavaScript?
Also, what is the \"context\" of the canvas I keep reading about?
The answers mentioning canvas.width
return the internal dimensions of the canvas, i.e. those specified when creating the element:
If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth
and .scrollHeight
:
var canvasElem = document.querySelector('canvas');
document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +
canvasElem.scrollWidth +
' x ' +
canvasElem.scrollHeight
var canvasContext = canvasElem.getContext('2d');
document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +
canvasContext.canvas.width +
' x ' +
canvasContext.canvas.height;
canvasContext.fillStyle = "#00A";
canvasContext.fillText("Distorted", 0, 10);