How to change the canvas size in HTML?

Viewed 34

I am making a game in HTML and JavaScript. I am trying to resize the standard canvas in chrome which is 300 x 150. I want to resize it to 1024 x 576.

Here is my code:

const canvas = document.querySelectory('#canvas');
const c = canvas.getContext('2d')

canvas.width = 1024
canvas.height = 576
<canvas></canvas>

1 Answers

The problem was with the following line:

const canvas = document.querySelectory('#canvas');

The 'y' at the end of querySelector is a typo and should be removed.

# before canvas indicates id="canvas" should exist in the HTML, but that is not the case, so the # is not necessary and we can select the canvas element itself.

I added a black border to the canvas and set the background to green. The effect of setting the height and width is clearly visible.

const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');

canvas.style.background = 'green';
canvas.style.border = 'solid 3px black';

canvas.width = 1024;
canvas.height = 576;
<canvas></canvas>

Related