Search code examples
javascripthtmlhtml5-canvas

null error when using document.getElementById()


I'm trying to to draw a circle using the canvas tag using javascript, but I am constantly getting an error stating c is null when using document.getElementById(). I initially assumed this was because of the HTML content not loading fast enough, so I used window.onload but this did not change anything. Any help would be appreciated:

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Title</title>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="description" content="" />
        <link rel="stylesheet" href="css/stylesheet.css" />
        <link rel="icon" href="images/favicon.png" />

        <script src="javascript/script.js"></script>
    </head>
    
    <body>

        <canvas id="myLogo" width="150" height="150"></canvas>
        
    </body>
</html>

Javascript:

window.onload = scripting();

function scripting() {

    logo();

    function logo() {

        console.log('called logo()');
        
        var c = document.getElementById("myLogo");
        var ctx = c.getContext("2d");
        ctx.beginPath();
        ctx.arc(100, 75, 50, 0, 2 * Math.PI);
        ctx.stroke(); 
    }
}

The above code results in the following error, referencing lines 12:13:


Solution

  • Have you tried moving your <script> block to the bottom of (last item in) <body> ?