Chronium
Chronium

Reputation: 1046

Cannot call method 'appendChild' of null

I need some help with my problem; it seems like Chrome doesn't like to run this code, but on Firefox it works:

function createContext(width, height) {
    var canvas = document.createElement('canvas');
    canvas.id = "1";
    canvas.width = width;
    canvas.height = height;
    document.body.appendChild(canvas);
    return canvas.getContext('2d');
}

Upvotes: 0

Views: 490

Answers (3)

skos
skos

Reputation: 4212

Perhaps you could try this -

window.onload=function(){
    createContext(100, 200);
};

function createContext(width, height) {
    var canvas = document.createElement('canvas');
    canvas.id = "1";
    canvas.width = width;
    canvas.height = height;
    document.body.appendChild(canvas);
    return canvas.getContext('2d');
}

Check this fiddle - http://jsfiddle.net/j4c7U/82/

Upvotes: 0

n1kkou
n1kkou

Reputation: 3142

You should also call the createContext() function. Fiddle: http://jsfiddle.net/gXm8L/

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

You must wait for document.body to actually exist before calling your function.

The simplest way is to invoke this code at the end of your HTML markup, rather than in the <head>

Upvotes: 1

Related Questions