JS中如何从root/L2目录访问root/inventoryAssets的资源?
可行的实现方案
因为浏览器端纯JS无法直接读取本地文件夹目录结构,以下是几种实用的落地方案:
方案1:手动维护物品路径清单(最适合新手)
直接在代码里定义包含所有物品图片相对路径的数组,你的代码位于root/L2,所以图片的相对路径格式为../inventoryAssets/[图片文件名],循环遍历数组即可批量加载图片。
示例代码:
// 定义所有物品图片的相对路径 const inventoryItems = [ "../inventoryAssets/sword.png", "../inventoryAssets/potion.png", "../inventoryAssets/shield.png" ]; // 批量加载并缓存图片 const loadedImages = {}; inventoryItems.forEach(itemPath => { const img = new Image(); img.src = itemPath; img.onload = () => { loadedImages[itemPath] = img; // 加载完成后可渲染到背包界面 console.log(`加载完成:${itemPath}`); }; img.onerror = () => { console.error(`加载失败:${itemPath}`); }; });
方案2:用JSON配置文件管理物品(更易维护)
在root/inventoryAssets目录下创建items.json配置文件,统一存储物品的路径、名称等信息,再通过fetch请求该文件批量加载图片。
步骤1:创建items.json配置文件
{ "items": [ { "name": "剑", "imgPath": "sword.png" }, { "name": "药水", "imgPath": "potion.png" }, { "name": "盾牌", "imgPath": "shield.png" } ] }
步骤2:JS代码加载逻辑
// 请求配置文件 fetch("../inventoryAssets/items.json") .then(response => response.json()) .then(data => { const loadedImages = {}; data.items.forEach(item => { // 拼接完整相对路径 const fullPath = `../inventoryAssets/${item.imgPath}`; const img = new Image(); img.src = fullPath; img.onload = () => { loadedImages[item.name] = img; // 此处可将物品渲染至背包界面 console.log(`加载完成:${item.name}`); }; }); }) .catch(err => console.error("加载配置文件失败:", err));
方案3:Node.js/桌面游戏场景(如Electron)
如果你的游戏是基于Node.js的桌面应用(比如Electron),可使用Node.js的fs模块直接遍历文件夹:
const fs = require('fs'); const path = require('path'); // 物品文件夹的绝对路径(根据项目实际路径调整) const inventoryDir = path.join(__dirname, '../inventoryAssets'); // 遍历文件夹筛选图片文件 fs.readdir(inventoryDir, (err, files) => { if (err) throw err; const imageFiles = files.filter(file => file.endsWith('.png') || file.endsWith('.jpg') || file.endsWith('.webp') ); // 批量加载图片(Electron环境可直接使用Image对象) imageFiles.forEach(file => { const img = new Image(); img.src = path.join(inventoryDir, file); // 后续渲染或缓存逻辑 }); });
内容的提问来源于stack exchange,提问作者Michael Kielbasinski
相关产品推荐
相关产品推荐

