导入 js 文件后,我的画布上没有任何显示

我正在尝试制作一个 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);

汽车.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


幕布斯7119047
浏览 74回答 2
2回答

富国沪深

您需要将 type="module" 添加到脚本标签<script&nbsp;type="module"&nbsp;src='index.js'></script>并修复导入import&nbsp;car&nbsp;from&nbsp;"./car.js";

子衿沉夜

您需要将您的项目放在任何本地服务器中,例如 XAMP、MAMP、WAMP,并将“.js”添加到 index.js 文件中的汽车导入中,运行您的本地服务器,它就会工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript