You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中将精灵图上传至Canvas时图片不显示问题求助

问题解决方法

核心问题:图片加载的异步性

你直接调用drawScene()时,图片还未完成加载,Canvas无法绘制未加载完成的资源,必须等待图片加载完毕后再执行绘制操作。

路径优化:替换绝对路径为相对路径

本地开发使用绝对路径(如S:/xxx)易触发文件访问权限问题,换成相对路径更可靠。根据你的项目结构,图片的相对路径应为./OTHER/IMAGES/UAVBASED.png(假设HTML文件位于项目根目录)。

修正后的代码

HTML(规范canvas属性写法,移除单位)

<!DOCTYPE html>
<html>
    <head>
        <title>Game of Drones</title>
        <link rel="stylesheet" href="./CSS/style.css">
    </head>
    <body>
        <canvas id="field" width="800" height="600"></canvas>
        <script src="./JS/main.js"></script>
    </body>
</html>

JavaScript(添加图片加载完成事件)

let field = document.querySelector("#field");
let ctx = field.getContext("2d");

let UAV = new Image();
// 使用相对路径
UAV.src = "./OTHER/IMAGES/UAVBASED.png";

class Star {
    constructor(xCoord, yCoord, radius) {
        this.x = xCoord;
        this.y = yCoord;
        this.R = radius;
    }

    draw() {
        ctx.fillStyle = "grey";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.R, 0, 2 * Math.PI);
        ctx.fill();
        ctx.closePath();
    }
}

let stars = [];

function drawScene() {
    ctx.drawImage(UAV, 250, 250);
}

// 等待图片加载完成后再执行绘制
UAV.onload = function() {
    drawScene();
};

额外检查项

  • 确认图片文件名、后缀完全正确(部分系统区分大小写,比如.PNG和.png会被视为不同文件)
  • 建议用本地服务器打开页面(如VSCode的Live Server插件),避免直接打开HTML文件时的跨域/文件权限限制

内容的提问来源于stack exchange,提问作者DarkKnight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:10:31