I am trying to code a game in JS. I created a html file with a canvas, a main.js file where i will write the code. Now i want to get the context of the canvas so I can draw on it.
The problem is, when I create a variable "canvas" in main.js, and give it the value : document.getElementById('gameScreen'), and print it in the console to see if it works, I just don't get anything. No error, no message, the console stays empty. Furthermore, when I try to get the context of the canvas, my editor (visual studio code, portable version) doesn't recognise the getContext method.
First I thought my code was wrong, so I tried writing it into a tag. And the code worked. So my javascript code only works when in the html file. I have had this problem for a long time, but I only had short scripts, so there wasn't any problem in including it in a tag. But now, coding a game in a single file is impossible as it gets really messy really fast. I tried running the html file in other browsers (Firefox, Chrome, Chromium, internet Explorer) but I always get the same result.
Here is the html file:
<html>
<head>
<meta charset="utf-8">
<title>Game - Platformer</title>
<script src="/js_source/main.js"></script>
<link rel="stylesheet" type="text/css" href="/css/platformer.css">
</head>
<body>
<canvas id="gameScreen"></canvas>
</body>
</html>
And here the JS file:
canvas = document.getElementById("gameScreen");
ctx = canvas.getContext("2d");
console.log(ctx);
I think it is a linking problem, is there something specific to write in the JS file to access the document? Obviously the code isn't executed; I suppose if the variable ctx doesn't contain anything the console should tell it, right?