我很难找到脚本无法加载到浏览器的原因。我正在为此运行实时服务器,但我仍然收到此错误。当在html中我有:"type="模块/javascript"'但他的剧本又没有加载。我能够成功地让其他相同格式的脚本运行,所以我确信这是我忽略的愚蠢的事情,但我似乎无法在不陷入疯狂困境的情况下找到好的信息。
我的html:1
<!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Bouncing Balls (Object Oriented Programming)</title>
6 <link rel="stylesheet" href="style.css">
7 <script type="module" src="index.js"></script>
8 </head>
9 <body>
10 <a href="bouncingBalls.html">Previous Page</a>
11
12 <div class="canvas-container">
13 <canvas id="gameCanvas" width="1200" height="900"></canvas>
14 </div>
15
16 </body>
17 </html>
// index.js file:
1 import Scene from './Scene.js';
2
>> 3 const animation = new Scene();
// Scene.js file:
import Ball from './Ball';
// Default values:
const defaultConfig = {
width: 500,
height: 500,
gravity: 0.25,
friction: 0.98
}
// Classes are functions that create Objects:
export class Scene {
// Constructor function is equivalent to init()
constructor (canvasId = 'gameCanvas', config) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext('2d');
// Settings; merge default config and any passed in config by *spreading* them:
this.conifg = {
...defaultConfig,
...config
}
this.canvas.width = this.config.width;
this.canvas.height = this.config.height;
this.createBalls();
// Use arrow function so we can use 'this' property
document.addEventListener('DOMContentLoaded', () => this.update());
}
createBalls() {
// Scene config:
const { config } = this;
// Random colors:
const colors = ['purple', 'red', 'blue', 'brown'];
// Array of ball obejcts:
const balls = [];
for (let i = 0; i < 20; i++) {
balls.push(new Ball(
// Random X and Y positions:
Math.random() * config.width, Math.random() * config.height,
// scen conifg:
{
// default width, height, friciton:
...config,
// random + or - gravity:
gravity: config.gravity * (Math.floor(Math.random() * 2) || -1)
},
// ball properties:
{
//extra bouncy:
bounce: 0.90,
radius: Math.random() * 20 + 10,
color: colors[Math.floor(Math.random() * colors.length)]
}
));
}
this.balls = balls;
}
update() {
// *Destructure* scene's variables:
const { ctx, config, balls } = this;
// Queue the next update:
window.requestAnimationFrame(() => this.update());
// clear canvas:
ctx.clearRect(0, 0, config.width, config.height);
// update my balls!
balls.forEach(ball => ball.update());
// Draw objects:
balls.forEach(ball => ball.draw(ctx));
}
}
export default Scene;
更改此行
import Ball from './Ball';
对此:
import Ball from './Ball.js'; // added .js to end of Ball
您的脚本正在尝试读取名为"Ball"的html文件,而不是JavaScript文件