How do I define the width and height of a HTML canvas in a JavaScript variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How do I define the width and height of a HTML canvas in a JavaScript variable?

I would like the width and height of the canvas to be equal to the specific variables in JavaScript. I have written the following code: <html> <body> <canvas id="background" width="canvasWidth" height="canvasHeight"></canvas> <script> const canvasWidth = 1660; const canvasHeight = 700; canvas = document.getElementById('background'); canvasContext = canvas.getContext('2d'); canvasContext.fillStyle = 'black'; canvasContext.fillRect(0,0,canvasWidth,canvasHeight); </script> <body> </html>

31st May 2019, 5:13 PM
Sem Pepels
Sem Pepels - avatar
2 Answers
+ 5
If you want to add an attribute to a HTML element, you can use the setAttribute() method which takes in two arguments. (1) The attribute's name. (2) The attributes value. Using setAttribute() is good for every html attribute except for styling, use the style property along with the specific property in camel case (thisIsCamelCase) with the value: Do: const canvas = document.getElementById('background'); const canvasWidth = canvas.width = `1660px`; const canvasHeight = canvas.height = `700px`;
31st May 2019, 10:20 PM
let whoAmI = "?"
+ 2
Add px or % after the value.. That works
28th Jun 2019, 1:05 AM
Ekok Emmanuel Ajom
Ekok Emmanuel Ajom - avatar