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:
xxxxxxxxxx
1
var canvas = document.querySelector('#canvas-id');
2
3
var width = canvas.width;
4
var height = canvas.height;
Note: This approach doesn't include
padding
andborder
properties.
or:
xxxxxxxxxx
1
var canvas = document.querySelector('#canvas-id');
2
3
var width = canvas.getBoundingClientRect().width;
4
var height = canvas.getBoundingClientRect().height;
In this example, we present how to get canvas size using width
and height
properties.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width="400" height="100"></canvas>
12
13
<script>
14
15
var canvas = document.querySelector('#my-canvas');
16
17
var width = canvas.width;
18
var height = canvas.height;
19
20
console.log('width=' + width + ', height=' + height);
21
22
</script>
23
</body>
24
</html>
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
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width="400" height="100"></canvas>
12
13
<script>
14
15
var canvas = document.querySelector('#my-canvas');
16
17
var width = canvas.getBoundingClientRect().width;
18
var height = canvas.getBoundingClientRect().height;
19
20
console.log('Canvas size including border:\n');
21
console.log('width=' + width + ', height=' + height);
22
23
</script>
24
</body>
25
</html>
When the canvas size is not specified, the properties will return the following values:
width
= 300px,height
= 150px.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas"></canvas>
12
13
<script>
14
15
var canvas = document.querySelector('#my-canvas');
16
17
var width = canvas.width;
18
var height = canvas.height;
19
20
console.log('width=' + width + ', height=' + height);
21
22
</script>
23
</body>
24
</html>