javascript - 使用上下文在 Canvas 上抛出 HTML5 元素

标签 javascript html canvas

一个代码示例,我想使用上下文绘制一个对象。

它在 Firefox 15 上抛出错误:

TypeError: el is null
[Break On This Error]   

GetElementById 已正确抓取,但抛出错误。我也在检查头、脚本标签,它是正确的。我还将脚本代码放在 head 标记中,结果是一样的。

这是代码示例:

<!doctype html>
<html lang="en">
    <head>
        <title>Canvas</title>
        <meta charset="utf-8">  
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
    </head>
    <body>
        <script>
            var el = document.getElementById("myCanvas"); // this thrown empty

            var context = el.getContext("2d");

            context.fillStyle = '#00f';
            context.strokeStyle = '#f00';
            context.lineWidth = 4;

            context.beginPath();
            context.moveTo(10, 10);
            context.lineTo(100, 10);
            context.lineTo(10, 100);
            context.lineTo(10, 10);
            context.fill();
            context.stroke();
            context.closePath(); 
        </script>
        <canvas id="myCanvas" width="600" height="200"></canvas>
    </body>
</html>

最佳答案

您的 Canvas 元素出现在 <script> 之后堵塞。当脚本代码运行时,它(<canvas>)还不在 DOM 中,所以 getElementById()不会找到它。

<canvas> 脚本之前再试一次。

DOM 是在页面被解析时逐步构建的。然而,一旦 </script> 出现,脚本 block 就会被评估。找到结束标记。因此,当您的脚本执行时 <canvas>还没有被浏览器解释。

关于javascript - 使用上下文在 Canvas 上抛出 HTML5 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12998108/

相关文章:

javascript - 未处理的PromiseRejectionWarning : Unhandled promise rejection (rejection id: 1) in Node. JS

javascript - 如何在 DOM 元素的 ng-bind-html 中编译 Angular 表达式 {{scope.somevalue}} ?

javascript - 使用 Jest-Puppeteer (Javascript) 进行 HTML Canvas 测试

javascript - Onclick 在 JavaScript Canvas 中创建的图像

javascript - 仅将样式应用于可编辑内容中的选定文本 <p>

javascript - React Native listView 项目删除未正确删除项目

javascript - 状态数组的变化不会通过 Prop 改变 child

html - 在 Bootstrap 3 中使用 col-push 和 col-pull 操作列顺序

javascript - 如何通过单击页面关闭覆盖

javascript - Canvas 游戏中的图像闪烁