当我运行下面的代码时,我得到的变量表面为“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/