Search code examples
javascriptcanvashtml5-canvas

Problems using the Canvas element


I'm having trouble using the Canvas element in all my browsers. The web console says a "script error" but I'm using the same method I used in other projects which worked great, my code is as follows:

<!DOCTYPE html>
<html lang="pt-BR">
<head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="script.js"></script>
</head>
<body>
        <canvas id="canvas"></canvas>
</body>
</html> 

And the javascript file:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);

*My browsers support the Canvas element

*The line of the javascript who contain the "const ctx" its appointed with error by my Web console, what i did?


Solution

  • The problem is that the JS file is loading before the canvas. To fix this, move the script tag to the body:

    <body>
        <canvas id="canvas"></canvas>
        <script src="script.js"></script>
    </body>
    

    Alternatively, if you want to keep the script tag in the head, move the canvas code to window.onload:

    window.onload = function() {
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = 'green';
        ctx.fillRect(10, 10, 100, 100);
    }