简体   繁体   中英

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

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>

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM