gpt4 book ai didi

javascript - getElementById 为 Canvas 元素返回 null

转载 作者:行者123 更新时间:2023-11-30 12:45:40 26 4
gpt4 key购买 nike

当我运行下面的代码时,我得到的变量表面为“null”。谁能告诉我我做错了什么?

<html>

<body>
<script>
var surface = document.getElementById("myCanvas");
console.log("surface: " + surface);
</script>

<canvas id="myCanvas" width="300" height="150">
<p>Your browser doesn't support canvas.</p>
</canvas>
</body>

</html>

最佳答案

当您尝试获取该元素时,该元素尚不存在,请移动脚本标签,使该元素在 DOM 中位于它之前

<html>

<body>
<canvas id="myCanvas" width="300" height="150">
<p>Your browser doesn't support canvas.</p>
</canvas>

<script>
var surface = document.getElementById("myCanvas");
console.log("surface: " + surface);
</script>
</body>

</html>

关于javascript - getElementById 为 Canvas 元素返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22571445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com