使用 HTML 绘制图形时 canvas
放置时<script>
在您文档的 <head>
中不起作用。例如:
<head>
<script>
var canvas = document.getElementById("myCanvas");
if(canvas.getContext("2d"))
var ctx = canvas.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</head>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
</body>
但是当 <script>
时,您确实得到了预期的结果放在 <body>
里面。因为您可以放置 <script>
里面的任何地方<head>
那么为什么这不适用于 canvas
?提前致谢!
最佳答案
您的 HTML 尚未呈现,因此 document.getElementById("myCanvas") 找不到 myCanvas 元素。然而,如果您将代码放在后面,则会呈现 HTML,因此它能够找到它。
如果您想将其放置在头部,请在文档加载时使用事件来渲染它,以便它在 HTML 渲染后执行。
检查此代码:
<head>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var canvas = document.getElementById("myCanvas");
if(canvas.getContext("2d"))
var ctx = canvas.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
});
</script>
</head>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
</body>
关于javascript - 当脚本放置在 head 标签内时,为什么 HTML5 Canvas 不绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41912530/