When the width and height of the canvas are set with the style tag, the canvas is stretched.
The solution is to use the setAttribute method and add the with and height attributes to the canvas tag.
This is the result of setting only the background color using the style tag without setting the width and height on the canvas.
The default size of the canvas is set to 300px horizontally and 150px vertically.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#canvas {
background-color: darkgrey;
}
</style>
</head>
<body>
<canvas id="canvas">
</canvas>
<script>
function draw() {
const canvas = document.getElementById('canvas')
if(canvas.getContext){
const ctx = canvas.getContext('2d')
ctx.font = '48px serif';
ctx.fillText('Hello world', 10, 50);
}
}
draw()
</script>
</body>
</html>
This is the result of the addition of setting the width of the canvas to 500px and the height to 500px using the style tag.
If the style tag is used, as the width and height of the canvas increase, the contents of the canvas also increase.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#canvas {
background-color: darkgrey;
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<canvas id="canvas">
</canvas>
<script>
function draw() {
const canvas = document.getElementById('canvas')
if(canvas.getContext){
const ctx = canvas.getContext('2d')
ctx.font = '48px serif';
ctx.fillText('Hello world', 10, 50);
}
}
draw()
</script>
</body>
</html>
If you set the width and height attributes on the canvas using the setAttribute method, the canvas content does not increase.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#canvas {
background-color: darkgrey;
}
</style>
</head>
<body>
<canvas id="canvas">
</canvas>
<script>
function draw() {
const canvas = document.getElementById('canvas')
canvas.setAttribute('width', '500')
canvas.setAttribute('height', '500')
if(canvas.getContext){
const ctx = canvas.getContext('2d')
ctx.font = '48px serif';
ctx.fillText('Hello world', 10, 50);
}
}
draw()
</script>
</body>
</html>
By setting the width and height properties of the tag on the canvas, you can solve the problem of increasing the contents of the canvas.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#canvas {
background-color: darkgrey;
}
</style>
</head>
<body>
<canvas id="canvas" width="500px" height="500px">
</canvas>
<script>
function draw() {
const canvas = document.getElementById('canvas')
if(canvas.getContext){
const ctx = canvas.getContext('2d')
ctx.font = '48px serif';
ctx.fillText('Hello world', 10, 50);
}
}
draw()
</script>
</body>
</html>