[javascript] How do I get the width and height of a HTML5 canvas?

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?

This question is related to javascript html canvas

The answer is


The context object allows you to manipulate the canvas; you can draw rectangles for example and a lot more.

If you want to get the width and height, you can just use the standard HTML attributes width and height:

var canvas = document.getElementById( 'yourCanvasID' );
var ctx = canvas.getContext( '2d' );

alert( canvas.width );
alert( canvas.height ); 

Here's a CodePen that uses canvas.height/width, CSS height/width, and context to correctly render any canvas at any size.

HTML:

<button onclick="render()">Render</button>
<canvas id="myCanvas" height="100" width="100" style="object-fit:contain;"></canvas>

CSS:

canvas {
  width: 400px;
  height: 200px;
  border: 1px solid red;
  display: block;
}

Javascript:

const myCanvas = document.getElementById("myCanvas");
const originalHeight = myCanvas.height;
const originalWidth = myCanvas.width;
render();
function render() {
  let dimensions = getObjectFitSize(
    true,
    myCanvas.clientWidth,
    myCanvas.clientHeight,
    myCanvas.width,
    myCanvas.height
  );
  myCanvas.width = dimensions.width;
  myCanvas.height = dimensions.height;

  let ctx = myCanvas.getContext("2d");
  let ratio = Math.min(
    myCanvas.clientWidth / originalWidth,
    myCanvas.clientHeight / originalHeight
  );
  ctx.scale(ratio, ratio); //adjust this!
  ctx.beginPath();
  ctx.arc(50, 50, 50, 0, 2 * Math.PI);
  ctx.stroke();
}

// adapted from: https://www.npmjs.com/package/intrinsic-scale
function getObjectFitSize(
  contains /* true = contain, false = cover */,
  containerWidth,
  containerHeight,
  width,
  height
) {
  var doRatio = width / height;
  var cRatio = containerWidth / containerHeight;
  var targetWidth = 0;
  var targetHeight = 0;
  var test = contains ? doRatio > cRatio : doRatio < cRatio;

  if (test) {
    targetWidth = containerWidth;
    targetHeight = targetWidth / doRatio;
  } else {
    targetHeight = containerHeight;
    targetWidth = targetHeight * doRatio;
  }

  return {
    width: targetWidth,
    height: targetHeight,
    x: (containerWidth - targetWidth) / 2,
    y: (containerHeight - targetHeight) / 2
  };
}

Basically, canvas.height/width sets the size of the bitmap you are rendering to. The CSS height/width then scales the bitmap to fit the layout space (often warping it as it scales it). The context can then modify it's scale to draw, using vector operations, at different sizes.


None of those worked for me. Try this.

console.log($(canvasjQueryElement)[0].width)

I had a problem because my canvas was inside of a container without ID so I used this jquery code below

$('.cropArea canvas').width()

Well, all the answers before aren't entirely correct. 2 of major browsers don't support those 2 properties (IE is one of them) or use them differently.

Better solution (supported by most browsers, but I didn't check Safari):

var canvas = document.getElementById('mycanvas');
var width = canvas.scrollWidth;
var height = canvas.scrollHeight;

At least I get correct values with scrollWidth and -Height and MUST set canvas.width and height when it is resized.


now starting 2015 all (major?) browsers seem to alow c.width and c.height to get the canvas internal size, but:

the question as the answers are missleading, because the a canvas has in principle 2 different/independent sizes.

The "html" lets say CSS width/height and its own (attribute-) width/height

look at this short example of different sizing, where I put a 200/200 canvas into a 300/100 html-element

With most examples (all I saw) there is no css-size set, so theese get implizit the width and height of the (drawing-) canvas size. But that is not a must, and can produce funy results, if you take the wrong size - ie. css widht/height for inner positioning.


The answers mentioning canvas.width return the internal dimensions of the canvas, i.e. those specified when creating the element:

<canvas width="500" height="200">

If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth and .scrollHeight:

_x000D_
_x000D_
var canvasElem = document.querySelector('canvas');_x000D_
document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +_x000D_
      canvasElem.scrollWidth +_x000D_
      ' x ' +_x000D_
      canvasElem.scrollHeight_x000D_
_x000D_
var canvasContext = canvasElem.getContext('2d');_x000D_
document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +_x000D_
      canvasContext.canvas.width +_x000D_
      ' x ' +_x000D_
      canvasContext.canvas.height;_x000D_
_x000D_
canvasContext.fillStyle = "#00A";_x000D_
canvasContext.fillText("Distorted", 0, 10);
_x000D_
<p id="dom-dims"></p>_x000D_
<p id="internal-dims"></p>_x000D_
<canvas style="width: 100%; height: 123px; border: 1px dashed black">
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to canvas

How to make canvas responsive How to fill the whole canvas with specific color? Use HTML5 to resize an image before upload Convert canvas to PDF Scaling an image to fit on canvas Split string in JavaScript and detect line break Get distance between two points in canvas canvas.toDataURL() SecurityError Converting Chart.js canvas chart to image using .toDataUrl() results in blank image Chart.js canvas resize