Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么画布是未定义的_Javascript_Html - Fatal编程技术网

Javascript 为什么画布是未定义的

Javascript 为什么画布是未定义的,javascript,html,Javascript,Html,这里我使用javascript创建canvas元素,如下所示 canvas = document.createElement("canvas"); canvas.id = "canvas"; canvas.height = "450"; canvas.width = "745"; canvas.style="background- color:#ffffff"; canvas = document.getElementById("canvas"); console.log(canvas); j

这里我使用javascript创建canvas元素,如下所示

canvas = document.createElement("canvas");
canvas.id = "canvas";
canvas.height = "450";
canvas.width = "745";
canvas.style="background- color:#ffffff";
canvas = document.getElementById("canvas"); 
console.log(canvas);
jq("#container").append (canvas);
这里画布显示了未定义和我创建时的状态,如下所示

canvas = document.createElement("canvas");
canvas.id = "canvas";
canvas.height = "450";
canvas.width = "745";
canvas.style="background- color:#ffffff";
console.log(canvas);
jq("#container").append (canvas);

在这里它很好用。为什么上面的一个不起作用

第一个版本希望画布已通过检查
document.getElementById()
呈现到DOM。但是,尽管元素已完全形成,但它从未被呈现到DOM中。来自
canvas=document.getElementById(“canvas”)的结果
是指它被
null
覆盖,然后这就是您试图发送给jquery的内容

在第二个示例中,元素作为参数传递给jquery的append方法,该方法随后将元素追加到页面“#container”上已经存在的元素中

换句话说,不同之处在于版本1使用了以下内容:

jq("#container").append (null);
jq("#container").append (canvas);
而版本2使用了以下内容:

jq("#container").append (null);
jq("#container").append (canvas);

document.getElementById()
将只查找附加到
文档
树的元素

在第一个示例中,
在被分配丢弃之前,在内存中保持分离的节点:

canvas = document.getElementById("canvas"); // null
// replaces the reference to the `<canvas>`, allowing garbage collection

在第一种情况下,在将其添加到DOM之前,您正在执行
document.getElementById
。所以它当然是未定义的。尽管如此,我不知道当您已经有了对它的引用时,为什么要尝试使用
getElementById
获取对它的引用。或者为什么要将jquery与普通javascript DOM方法混合使用。在将其添加到文档之前,
document.getElementById
将找不到该节点。从技术上讲,
getElementById
返回
null
未定义的
@Bergi-谢谢,我会澄清:)