gpt4 book ai didi

javascript - 为什么这个 HTML5 Canvas 不显示?

转载 作者:行者123 更新时间:2023-11-28 11:06:02 31 4
gpt4 key购买 nike

<!doctype html>
<html>
<head>
<title>Canvas test</title>
</head>
<body>
<script type="text/javascript">
c = getElementById('canvas');
ctx = c.getContext("2d")'
ctx.fillRect(10,10,10,10);
</script>
<canvas id="canvas" height ="100" width = "100"></canvas>
</body>
</html>

我在 Chrome 和 IE 9 上尝试过此操作,但它们都没有显示任何内容。你知道为什么这不起作用吗?

这可能是一些愚蠢的事情,我的 friend 让我发布这个,因为他懒得注册,但我自己无法弄清楚。

最佳答案

您需要将代码放在 onload 中功能。

例如:

window.onload = function() {
c = document.getElementById('canvas');
ctx = c.getContext("2d");
ctx.fillRect(10,10,10,10);
};

这样做的原因是因为您的 javascrpt 代码将在 <canvas> 之前运行。渲染,并且您希望它运行afterwords

演示:http://jsfiddle.net/maniator/nCf7Y/

关于javascript - 为什么这个 HTML5 Canvas 不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589156/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com