无法调用方法'appendChild'为null

Cannot call method 'appendChild' of null

本文关键字:null appendChild 调用 方法      更新时间:2023-09-26

我的问题需要一些帮助;Chrome似乎不喜欢运行这些代码,但在Firefox上它是有效的:

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

在调用函数之前,必须等待document.body实际存在。

最简单的方法是在HTML标记的末尾调用此代码,而不是在<head>

中调用

您还应该调用createContext()函数。Fiddle:http://jsfiddle.net/gXm8L/

也许你可以试试这个-

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

检查这个小提琴-http://jsfiddle.net/j4c7U/82/