javascript - getElementById 为 Canvas 元素返回 null

标签 javascript html web null

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

相关文章:

javascript - 当查询有变量时,PHP/Javascript + MySQL 数据不会被检索

javascript - 网站下拉按钮组件名称

html - 输入中心,标签在左上方

javascript - jQuery tablesorter 使用分页和 sortForce

javascript - 为什么 Chrome 将数据 URL 评为交叉来源?

javascript - 我无法让这个 Jquery Image ComboBox 工作

javascript - 具有动态 templateUrl 的 angularjs 组件

html - 如何使用 Rails 提供静态 html 页面?

firefox - 在页面内播放ogg?

html - 每个网页的最大 <iFrame> 标记数