0

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');
}
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Chronium
  • 906
  • 9
  • 12
  • 1
    it's works well in my chrome console,try run your code after DOM ready – yoyo Dec 12 '13 at 11:22
  • possible for duplicate http://stackoverflow.com/questions/8670530/javascript-error-cannot-call-method-appendchild-of-null http://stackoverflow.com/questions/19086159/uncaught-typeerror-cannot-call-method-appendchild-of-null http://stackoverflow.com/questions/14946428/how-to-fix-uncaught-typeerror-cannot-call-method-appendchild-of-null http://stackoverflow.com/questions/9677879/cannot-call-method-appendchild-to-null-error-why – Mr.G Dec 12 '13 at 11:26

3 Answers3

1

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>

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

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

n1kkou
  • 3,096
  • 2
  • 21
  • 32
  • by definition, the error he's seeing doesn't occur until the function is actually called. – Alnitak Dec 12 '13 at 12:02
  • yes, in the fiddle i just provided, js was set to onDomready, so the element was found and worked. Did i say something wrong? – n1kkou Dec 12 '13 at 12:05
0

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/

skos
  • 4,102
  • 8
  • 36
  • 59