在外部文件中存储 Canvas js 无效。
如果在 html header 中提供了在 Canvas 上绘制的 javascript,则 Canvas 会正确绘制矩形。
下面显示的是有效的 html(即 html header 中的 javascript)
<!DOCTYPE html>
<html>
<head>
<script type="javascript/text" src="js/nodeServer.js"></script>
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 100, 50);
};
</script>
</head>
<body>
<h1>Canvas</h1>
<canvas
id="myCanvas"
width="300"
height="400"
style="background-color:#efefef;"
></canvas>
</body>
</html>
但是,当我将 js 传输到位于 js/main.js 的外部文件时,不会绘制矩形,但我认为引用很好。我不知道出了什么问题。
这是 header 中没有 javascript 的 html。
<html>
<head>
<script type="javascript/text" src="js/nodeServer.js"></script>
</head>
<body>
<h1>Canvas</h1>
<canvas
id="myCanvas"
width="300"
height="400"
style="background-color:#efefef;"
></canvas>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
这是 main.js 文件
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 50);
};
stack上还有其他相关的问题,但是答案并没有解决我的问题。我究竟做错了什么?我确定将我的 js 放在 window.onload 函数中,并且我在 html 正文底部引用了 Canvas 脚本。
谢谢你帮助我。
...有关可能相关或不相关的更多详细信息,我正在使用节点运行该应用程序。在与html文件相同目录的ubuntu终端中,
node js/nodeServer.js
(您必须安装节点才能执行此操作。)
这里是js/nodeServer.js文件的内容
const http = require("http");
const fs = require("fs");
fs.readFile("./index.html", function(err, html) {
if (err) {
throw err;
}
http
.createServer(function(request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
})
.listen(4242);
});
转到http://localhost:4242在 Chrome 等网络浏览器中。
更新: 我注意到当我打开 chrome 开发人员工具并转到“源代码”选项卡时,js/main.js 文件内容奇怪地显示了我的 html 代码,而不是 js 代码。下面我给出了显示 index.html 文件的源图片,然后是显示 main.js 文件的图片。 html 文件没有 SyntaxError,但是 main.js 文件显示 SyntaxError。
但是,我仔细检查以确保 main.js 是我操作系统上的 javascript 文件。
> cat js/main.js
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 50);
};
最佳答案
我猜因为您使用的是节点服务器,所以您不需要包含 <script type="javascript/text" src="js/nodeServer.js"></script>
行在你的 html 中。
您还需要通过您的 http 服务器提供 .js 文件,您只在代码示例中提供 html。
尝试使用类似 express https://expressjs.com/ 的东西处理为您的应用程序提供服务的文件。
如果您不需要节点服务器,您可以这样做:https://codesandbox.io/s/sleepy-chaum-5c8dk
关于javascript - 来自外部js文件的html5 Canvas 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024190/