-2
I’m learning to move the JS and I’m playing a little game.
I want to know what’s wrong with it, because I put the code exactly like the video class I watch, but it doesn’t run at all.
It was to create a screen in the center of the page, but nothing appears.
Follow the code below:
var canvas, ctx, LARGURA, ALTURA, frame = 0
function main() {
ALTURA = window.innerHeight
LARGURA = window.innerWidth
if (LARGURA >= 500) {
ALTURA = 600
LARGURA = 600
}
canvas = document.createElement("canvas")
canvas.width = LARGURA
canvas.height = ALTURA
canvas.style.border = "1px solid #000"
}
canvas {
position: absolute;
top: 0px;
bottom: 0px;
right: 0px;
left: 0px;
margin: auto;
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<title>Página Inicial</title>
</head>
<body>
<header>
<nav></nav>
</header>
<div></div>
<article>
<section>
</section>
</article>
<aside></aside>
<div></div>
<footer></footer>
</body>
</html>
Read: https://pt.meta.stackoverflow.com/questions/1084/comomos-formatter-questions-answers/1297#1297
– Augusto Vasques
You have to call the method
main()
you only declared it but did not make use of it.– Augusto Vasques
How do I call it in html?
– Isaac Bandim
Only invoke inside the script as a normal function like this
main()
or html put it into an event handleronclick="main()"
. PS: In the previous comment I called method, but it’s just a function.– Augusto Vasques
I put the main() at the end of the script, but still nothing appears...
– Isaac Bandim
Some things are missing from your code. I’m taking a look you need to attach the element created in
canvas = document.createElement("canvas")
the page like thisdocument.body.appendChild(canvas);
. Documentation ofappendChild
: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild– Augusto Vasques
canvas = Document.createelement("canvas") Document.body.appendchild(canvas) // error appears on the console " script.js:15 Uncaught Typeerror: Cannot read Property 'appendchild' of null "
– Isaac Bandim
Take a look at the answer I put is there is commented on. Click Run to see the result. On the upper right side of the display is the Whole Page button.
– Augusto Vasques
Running here, but mine does not run...appears the error msg on the console
– Isaac Bandim