Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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> ?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading