我是堆栈溢出的新手。我开始制作游戏,但我遇到了问题。我想将我的工作拆分为单独的文件,这样更容易。但是我遇到了一个问题:
Uncaught SyntaxError: Cannot use import statement outside a module
这是我收到此代码的错误:
main.js:
import Player from './modules/player';
window.addEventListener('load', main);
function main() {
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
function loadImg(src) {
let output = new Image();
output.src = src;
return output;
}
let player = new Player(loadImg('spaceship.png'), 20, 50, 80, 80);
function draw() {
ctx.clearRect(0, 0, canvas.clientWidth, canvas.height);
///
player.draw();
///
requestAnimationFrame(draw);
}
}
modules / player.js:
export default class Player {
constructor(cw, ch, sx, sy, img) {
this.cw = cw;
this.ch = ch;
this.sx = sx;
this.sy = sy;
this.img = img;
}
// DRAWING
draw() {
ctx.drawImage(this.img, this.x, this.y, this.sx, this.sy);
}
fill() {
ctx.fillRect(this.x, this.y, this.sx, this.sy);
}
stroke() {
ctx.strokeRect(this.x, this.y, this.sx, this.sy);
}
///
shoot() {}
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pucalka - Remastered</title>
</head>
<body>
<canvas width="800" height="600" id="canvas"></canvas>
<script src="main.js"></script>
</body>
</html>