Marin Sagovac
Marin Sagovac

Reputation: 3992

HTML5 Element thrown on canvas using context

An example of code, i want drawing an object using context.

It throws an error on Firefox 15:

TypeError: el is null
[Break On This Error]   

GetElementById has been properly grabbed, but it thrown an error. I'm also checking head, script tags and it's properly. I'm also put script code in head tag and result is same.

This is example of code:

<!doctype html>
<html lang="en">
    <head>
        <title>Canvas</title>
        <meta charset="utf-8">  
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
    </head>
    <body>
        <script>
            var el = document.getElementById("myCanvas"); // this thrown empty

            var context = el.getContext("2d");

            context.fillStyle = '#00f';
            context.strokeStyle = '#f00';
            context.lineWidth = 4;

            context.beginPath();
            context.moveTo(10, 10);
            context.lineTo(100, 10);
            context.lineTo(10, 100);
            context.lineTo(10, 10);
            context.fill();
            context.stroke();
            context.closePath(); 
        </script>
        <canvas id="myCanvas" width="600" height="200"></canvas>
    </body>
</html>

Upvotes: 1

Views: 94

Answers (1)

Pointy
Pointy

Reputation: 413996

Your canvas element appears after the <script> block. When the script code runs, it (the <canvas>) is not yet in the DOM, so getElementById() won't find it.

Put the <canvas> before the script and try it again.

The DOM is built incrementally as the page is parsed. Script blocks, however, are evaluated as soon as the </script> closing tag is found. Thus when your script is executed the <canvas> has not yet been interpreted by the browser at all.

Upvotes: 2

Related Questions