我试图制作一个javascript游戏,但是在导入js文件(car.js)之后,html画布上什么也没有显示出来,在导入car.js之前,所有的东西都显示出来了。 我目前有一个名为cargame的文件夹,它包括3个文件:car.js,firstgame.html和index.js。 我提供以下文件的内容。
firstgame.html
<!DOCTYPE html>
<html>
<head>
<title>Web Page Design</title>
<style>
#gamescreen{
border: 1px solid black;
}
#bgcolor{
background-color: #b4b4b4;
}
</style>
</head>
<body id="bgcolor">
<div align = "center" style="margin-top: 5%"><canvas id = "gamescreen" width = "500px" height = "600px"></canvas></div>
<script src="index.js"></script>
</body>
</html>
index.js
import car from "./car";
let canvas = document.getElementById("gamescreen");
let ctx = canvas.getContext('2d');
const GAME_WIDTH = 500;
const GAME_HEIGHT = 600;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width/3, canvas.height)
ctx.fillRect((canvas.width/3 + canvas.width/3), 0, canvas.width/3, canvas.height)
ctx.fillStyle = '#2a2a2a';
ctx.fillRect(canvas.width/3, 0, canvas.width/3, canvas.height)
ctx.clearRect(0,0,500,600)
let Car = new car(GAME_WIDTH, GAME_HEIGHT);
Car.draw(ctx);
car.js
export default class car{
constructor(gamewidth, gameheight){
this.width = 100;
this.height = 100;
this.position = {
x : gamewidth/2 - this.width/2,
y : gameheight - this.height - 10,
};
}
draw(ctx){
ctx.fillStyle = '#ff6969';
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
}
}
我的日志中出现以下错误
firstgame.html:1 Access to script at 'file:///C:/MY%20DATA/java%20projects/cargame/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
错误2
firstgame.html:19 GET file:///C:/MY%20DATA/java%20projects/cargame/index.js net::ERR_FAILED
您需要将type=“module”添加到脚本标记中
<script type="module" src='index.js'></script>
以及修复导入
import car from "./car.js";
您需要将您的项目放在任何本地服务器中,例如XAMP,MAMP,WAMP,并在index.js文件中的car导入中添加'.js',运行您的本地服务器,它就会工作。