getElementById为Canvas元素返回null

时间:2014-03-21 23:42:47

标签: javascript html html5 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>

2 个答案:

答案 0 :(得分:3)

当您尝试获取该元素时,该元素尚不存在,移动脚本标记以使元素位于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>

答案 1 :(得分:0)

将你的javascript放在画布之后,它很可能在画布在页面上呈现之前运行。