1

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

2 Answers 2

3

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

Live Demo

// Changed d to lower case
var ctx = canvasBg.getContext('2d');
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

D capital does not create instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.