Matty
Matty

Reputation: 15

Uncaught Type Error: Cannot set property of 'fillStyle' of null HTML5 Javascript

I'm playing with HTML5 canvas element with JavaScript. Now I can draw shapes to the canvas with internal JavaScript when I create an external file I get an Uncaught Type Error. All I want to do is draw a rectangle to my canvas through an external file.

Here is my HTML:

<!DOCTYPE HTML>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>FireBlaster</title>
</head>

<body style="background:#111111">
    <div id="inner">
        <button id="drawSquareBtn" type="button">Draw Square</button>
        <canvas id="myCanvas" width="600px" ; height="400px;" style=" dispaly:block; background:#000000; margin:8% 25%;"></canvas>
    </div>
    <script type="text/javascript" src="game.js"></script>
</body>

</html>

This is my JavaScript:

//JavaScript Document
var canvasBg = document.getElementById('myCanvas');
var ctx = canvasBg.getContext('2D');

function drawSquare() {

    alert('your pressed a button!');
    ctx.fillStyle = "#0A0AFF";
    ctx.fillRect(200, 150, 150, 50);
}
var drawSquareBtn = document.getElementById('drawSquareBtn');
drawSquareBtn.addEventListener('click', drawSquare, false);

Upvotes: 1

Views: 10776

Answers (2)

yogesh lodha
yogesh lodha

Reputation: 301

Wrong : -- var ctx = canvasBg.getContext('2D');

Right :-- var ctx = canvasBg.getContext('2d');

D capital does not create instance.

Upvotes: 0

Loktar
Loktar

Reputation: 35309

The d in getContext("2d") needs to be lower case.

Live Demo

// Changed d to lower case
var ctx = canvasBg.getContext('2d');

Upvotes: 3

Related Questions