Canvas 在 HTML 文件中工作,但在 javascript 文件中不工作

发布于 2024-12-26 04:17:41 字数 722 浏览 2 评论 0原文

我刚刚读完我的第一本 JavaScript 书《Head First HTML5》,我感觉自己很蠢。如果我将脚本放在 HTML 文件中,它可以工作,但不能在单独的 JavaScript 文件中工作。

HTML 文件:

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<script src="canArt.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas> 
</body>
</head>

JS 文件:

window.onload = init();
function init() {  
 var canvas = document.getElementById("canvas");  
 var ctx = canvas.getContext("2d");  

 ctx.fillStyle = "rgb(200,0,0)";  
 ctx.fillRect (10, 10, 55, 50);  

 ctx.fillStyle = "rgba(0, 0, 200, 0.5)";  
 ctx.fillRect (30, 30, 55, 50);  
} 

请帮忙。

I just finished my first JavaScript book, "Head First HTML5", and I'm feeling quite dumb. If i put the script in the HTML file it works, but doesn't work in a separate JavaScript file.

HTML file:

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<script src="canArt.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas> 
</body>
</head>

JS file:

window.onload = init();
function init() {  
 var canvas = document.getElementById("canvas");  
 var ctx = canvas.getContext("2d");  

 ctx.fillStyle = "rgb(200,0,0)";  
 ctx.fillRect (10, 10, 55, 50);  

 ctx.fillStyle = "rgba(0, 0, 200, 0.5)";  
 ctx.fillRect (30, 30, 55, 50);  
} 

please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恬淡成诗 2025-01-02 04:17:41

您通过包含括号并将 init 的结果(什么也没有)分配给 onload 处理程序来立即执行 init 函数...

更改:

window.onload = init();

到:

window.onload = init;

http://jsfiddle.net/sFmNw/

Your immediately executing the init function by including the parens and assigning the result of init, which is nothing, to the onload handler...

change:

window.onload = init();

to:

window.onload = init;

http://jsfiddle.net/sFmNw/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文