Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas.getContext('2d'); error

I am attempting to use this tutorial: http://html5gamedev.samlancashire.com/making-a-simple-html5-canvas-game-part-1-moving-a-sprite/

I have checked my code and it is exactly the same as the tutorial indicates (here it is: http://pastebin.com/1JsU28cx), however when ever I run the console gives me this error:"Uncaught TypeError: Cannot read property 'getContext' of null"

The error is in var ctx = canvas.getContext('2d'); I have seen a few similar questions, but they did not help...

I have no idea how to fix this...

Thanks!

Edit: I forgot to id canvas in the html

like image 494
Raven Avatar asked Sep 15 '26 12:09

Raven


1 Answers

From what I can ascertain from your javascript only pastebin, you either don't have a <canvas>, or its id is not "canvas". Make sure you change the id to "canvas", otherwise the document.getElementById will return null:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
 
canvas.width = 800;
canvas.height = 600;
 
var mySprite = {
    x: 200,
    y: 200,
    width: 50,
    height: 50,
    speed: 200,
    color: '#c00'
};
 
var keysDown = {};
window.addEventListener('keydown', function(e) {
    keysDown[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
    delete keysDown[e.keyCode];
});
 
function update(mod) {
    if (37 in keysDown) {
        mySprite.x -= mySprite.speed * mod;
    }
    if (38 in keysDown) {
        mySprite.y -= mySprite.speed * mod;
    }
    if (39 in keysDown) {
        mySprite.x += mySprite.speed * mod;
    }
    if (40 in keysDown) {
        mySprite.y += mySprite.speed * mod;
    }
}
 
function render() {
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = mySprite.color;
    ctx.fillRect(mySprite.x, mySprite.y, mySprite.width, mySprite.height);
}
 
function run() {
    update((Date.now() - time) / 1000);
    render();
    time = Date.now();
}
 
var time = Date.now();
setInterval(run, 10);
window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);
<!DOCTYPE html>
<html>
  <head>
    </head>
  <body>
    <canvas id="canvas"></canvas>
    </body>
  </html>
like image 140
user1823 Avatar answered Sep 18 '26 00:09

user1823