EN
JavaScript - get canvas size
0
points
In this article, we would like to show you how to get HTML canvas element size using JavaScript.
Quick solution:
var canvas = document.querySelector('#canvas-id');
var width = canvas.width;
var height = canvas.height;
Note: This approach doesn't include
padding
andborder
properties.
or:
var canvas = document.querySelector('#canvas-id');
var width = canvas.getBoundingClientRect().width;
var height = canvas.getBoundingClientRect().height;
1. Get canvas width and height
In this example, we present how to get canvas size using width
and height
properties.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="400" height="100"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var width = canvas.width;
var height = canvas.height;
console.log('width=' + width + ', height=' + height);
</script>
</body>
</html>
2. Get width and height dynamically
In this example, we present how to get canvas size using width
and height
properties with getBoundingClientRect()
method which returns DOM object including its padding
and border
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="400" height="100"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var width = canvas.getBoundingClientRect().width;
var height = canvas.getBoundingClientRect().height;
console.log('Canvas size including border:\n');
console.log('width=' + width + ', height=' + height);
</script>
</body>
</html>
3. Default width and height
When the canvas size is not specified, the properties will return the following values:
width
= 300px,height
= 150px.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var width = canvas.width;
var height = canvas.height;
console.log('width=' + width + ', height=' + height);
</script>
</body>
</html>