Wrong order of script and canvas

I want to get 2d context of canvas:

let canvas = document.getElementsByTagName("canvas")[0];
let ctx = canvas.getContext('2d');
console.log(ctx);

But every time it comes back null. After several hours of research I saw that the elements in the console have the wrong order.
First the script is executed and then the canvas is made.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <label for="userImage" class="custom-file-upload">
        <img src="img/buttons/upload.png" alt="upload" id="upload" />
    </label>
    <input id="userImage" type="file" />
    <img src="img/buttons/save.png" alt="save" id="save" />
    <canvas id="canvas"></canvas>

    <script type="module" src="js/client.js"></script>

</body>
</html>

Does anyone have similar experiences?

You can try putting the script tag into the <head> section instead.
However, I don’t think this should be an issue - when you add type="module", the browser will wait until it has parsed the entire HTML document before executing the script so it should already know about the canvas element. This is equivalent to adding a defer attribute.

So it should not matter where in the doc you place the script. However, it’s normal to put it in the head section.

Different pages

I cannot get 2d context still. I add defer and move script to the header. Type module I already have. But canvas.getContext(‘2d’); is still null

Well, again, it’s hard to help you without more info. Can you please share the entire code for you app? You can use something like Codesandbox or Codepen to share a live example. That way it’s much easier for people to help you.

I am reading and printing the mouse coordinates correctly in my “mousePos” header But when I draw on the canvas, using the same exact coordinates, by clicking and dragging, I am drawing to far to the bottom and to far to the right. I can fix this by not using style.canvas.width=“512px”, but then I can not set the size. The size must be 512 by 512.