Ridertvis
Ridertvis

Reputation: 223

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 works.

var canvas = document.getElementById("can").innerHTML;
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>

Upvotes: 1

Views: 20675

Answers (3)

Tony Chou
Tony Chou

Reputation: 604

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);

Upvotes: 3

Werner
Werner

Reputation: 2154

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>

Upvotes: 2

dferenc
dferenc

Reputation: 8126

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.

Upvotes: 2

Related Questions