为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

幕布斯7119047 2022-10-13 10:41:07
我正在尝试制作一个 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.jsimport 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);汽车.jsexport 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.错误 2firstgame.html:19 GET file:///C:/MY%20DATA/java%20projects/cargame/index.js net::ERR_FAILED
查看完整描述

2 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

您需要将 type="module" 添加到脚本标签

<script type="module" src='index.js'></script>

并修复导入

import car from "./car.js";


查看完整回答
反对 回复 2022-10-13
?
子衿沉夜

TA贡献1828条经验 获得超3个赞

您需要将您的项目放在任何本地服务器中,例如 XAMP、MAMP、WAMP,并将“.js”添加到 index.js 文件中的汽车导入中,运行您的本地服务器,它就会工作。


//img1.sycdn.imooc.com//63477ae200019d0506530354.jpg

查看完整回答
反对 回复 2022-10-13
  • 2 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信