Set Html5 Canvas Element Size
Set Canvas Size
The Canvas element has two sizes;
- Canvas element’s own size.
- Canvas element’s drawing surface size.
When you set the canvas element’s width
and height
properties; you set both Canvas element’s own size and Canvas element’s drawing surface size.
But if you set the sizes of the canvas using CSS, you will only set the Canvas element’s own size and the drawing surface size will not be affected.
The default canvas element size and it’s drawing surface size is 300 pixel width and 150 pixel height.
When a canvas element’s size does not match the size of its drawing surface, the browser scales the drawing surface to fit the element. Let’s see it in an example;
Code
<!DOCTYPE html>
<head>
<title>Set Canvas Element and Drawing Surface Size</title>
<style>
canvas {
background: #fff;
border: thin inset #acacac;
}
#canvas1 {
/* <-- Set canvas element size --> */
width: 300px;
height: 75px;
/* <-- Set canvas element size --> */
}
</style>
</head>
<body>
<canvas id="canvas1" width="100px" height="25px">
Your browser does not support HTML5 Canvas.
</canvas>
<br />
<canvas id="canvas2" width="100px" height="25px">
Your browser does not support HTML5 Canvas.
</canvas>
<script>
function setCanvasText(id) {
var canvas = document.getElementById(id),
context = canvas.getContext("2d");
context.font = '22pt Helvetica';
context.fillText("Canvas", 0, 24);
}
setCanvasText("canvas1");
setCanvasText("canvas2");
</script>
</body>
</html>
Result
Instead of using CSS to set the width and height of the canvas, it’s better to use the canvas element’s width and height attributes to size the element. If the canvas CSS width and height values and the canvas width and height attributes values does not match, the browser will scale the drawing surface to fit the element. This will cause unwanted effects.