+ 4

How can I set the dimensions of my canvas same as my screen size.

If I give it random dimensions then scrollbars appear on my webpage. I dont want that. I want it to be the same size as that of my screen. PS: My goal is to make a shape at the center of the screen by using height/2 and width/2 and for that I need the canvas to take the size of my screen.

25th May 2017, 11:21 AM
Casey McCray
Casey McCray - avatar
11 Antworten
+ 10
@Casey you have to modify the sizes of the canvas, i mean... not the context variable. :3 This is the easiest way, a professional work should resize the screen automatically: https://code.sololearn.com/WT0sb1EkTiAi/?ref=app
25th May 2017, 11:42 AM
Maz
Maz - avatar
+ 10
canvas.width = window.innerWidth; canvas.height = window.innerHeight;
25th May 2017, 11:27 AM
Maz
Maz - avatar
+ 6
you have a code on the playground we can play with?
25th May 2017, 11:34 AM
Burey
Burey - avatar
+ 6
window.onload = function() { canvas = document.getElementsByTagName("canvas")[0]; canvas.width = window.innerWidth; canvas.height = window.innerHeight; }
25th May 2017, 11:42 AM
The Coding Sloth
The Coding Sloth - avatar
+ 6
It's the first tag canvas in your DOM, if you have two tags and you want to select the second of them, you have to write [1] after the statement. For the third tag [2] and so on... You have no need to specify it for the getElementById( ) method, id is a unique element. ^^
25th May 2017, 5:56 PM
Maz
Maz - avatar
+ 6
The canvas can't work if you remove [0], because you storaged it in a variable with the getElementsByTagName( ) method, and it is the first canvas tag in your DOM. Yep, [0] for the getElementById( ) method, is useless. All this things are covered in the Javascript tutorial (Sololearn or w3schools), read something about DOM.
25th May 2017, 6:09 PM
Maz
Maz - avatar
+ 5
Show us your code please
25th May 2017, 11:35 AM
Tim G
Tim G - avatar
+ 3
@Maz, I tried that. I went on Stack Overflow to find answers and it suggesed the same thing. It didn't work. I did initialize the context variable (if thats what you're wondering) but idk what's wrong.
25th May 2017, 11:30 AM
Casey McCray
Casey McCray - avatar
+ 2
Alright man, Thanks for the help. I really appreciate it :D
25th May 2017, 6:10 PM
Casey McCray
Casey McCray - avatar
+ 1
@Maz, There is a line in the code that you posted: var canvas = document.getElementsByTagName("canvas")[0]; can you tell me what the [0] is for??
25th May 2017, 5:55 PM
Casey McCray
Casey McCray - avatar
+ 1
But if I remove the [0] then the canvas shrinks to like 15% in size. If getElementById is unique then [0] shouldn't have any purpose right?
25th May 2017, 6:07 PM
Casey McCray
Casey McCray - avatar