Skip to content Skip to sidebar Skip to footer

Canvas.getContext("2d"); Not Working

I am getting the following Error Error: Uncaught TypeError: Cannot read property 'innerHTML' of null at script.js:1 I have tried everything I could think of but nothing wor

Solution 1:

There are two things.
First, you don't need .innerHTML as other answers stated.
Second, you either have to run you script at the window load event like so:

window.addEventListener('load', function () {
    var canvas = document.getElementById("can");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = ("green");
    ctx.fillRect(0, 0, 300, 200);
});

Or you should load the javascript after the canvas tag.


Solution 2:

Okay there are two serious errors.

  1. You're trying to get the element before the DOM is fully loaded. Therefore the canvas note is not reachable. See addEventListener and DOMContentLoaded.
  2. Remove .innerHTML. getContext appends on the node not on the content.

document.addEventListener('DOMContentLoaded', function() {
    var canvas = document.getElementById("can");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "green";
    ctx.fillRect(0, 0, 300, 200);
});
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas  -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas>
</body>
</html>

Solution 3:

1. Script error when using canvas

Use var canvas = document.getElementById("can");

Not var canvas = document.getElementById("can").innerHTML();

See W3C - Canvas

2. Add an event listener when the document is ready, then execute your script

See W3C - DOM Event Listener example

function doSomething() {
    var canvas = document.getElementById("can");
    var ctx = canvas.getContext('2d');
    /*
    another scripts...
    */
}

window.addEventListener('onload', doSomething, false);

Post a Comment for "Canvas.getContext("2d"); Not Working"