Canvas 在 HTML 文件中工作,但在 javascript 文件中不工作
我刚刚读完我的第一本 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您通过包含括号并将
init
的结果(什么也没有)分配给onload
处理程序来立即执行init
函数...更改:
到:
http://jsfiddle.net/sFmNw/
Your immediately executing the
init
function by including the parens and assigning the result ofinit
, which is nothing, to theonload
handler...change:
to:
http://jsfiddle.net/sFmNw/