javascript - 从本地文件夹而不是 .js 中的网站加载图像
问题描述
我对编码非常陌生,特别是 .js 和 Stack。
所以我有这段代码,我想将图像更改为本地文件夹而不是 picsum。我已经搜索并尝试过,但无法做到。有没有办法以不会减慢程序速度的方式从本地文件夹加载图像?
希望我做对了,你能理解我的问题!
let imgs = [];
let num = 15;
function preload() {
for (let i = 0; i < num; i++) {
imgs[i] = loadImage("https://picsum.photos/400/400/?image=" + i * 10);
}
}
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
angleMode(DEGREES);
}
function draw() {
background(0,0,0);
orbitControl();
push();
translate(0, 0, -500);
let n = 0;
for (let j = 0; j < 20; j++) {
for (let i = 0; i < 20; i++) {
let x = map(i, 0, 20, -500, 500);
let y = map(j, 0, 20, -500, 500);
let z = sin(frameCount + j*10 + i * 10)*350+350;
push();
translate(x, y, z);
texture(imgs[n]);
plane(50, 50);
n = (n + 1) % imgs.length;
pop();
}
}
pop();
}
<html>
<head>
<script src="mySketch.js" type="text/javascript"></script><script src="https://cdn.jsdelivr.net/npm/p5@0.7.2/lib/p5.min.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
解决方案
这将为您提供一个带有键和与之对应的图像的字典。例如,images["imagefile1.png"] 将返回一个带有 src imagefile1.png 的图像。
const IMAGES_FILES = [
"imagefile1.png",
"imagefile2.png"
];
const images = {};
const downloadPromiseImage = Promise.all(IMAGES_FILES.map(downloadImage));
function downloadImage(imageName) {
return new Promise((resolve) => {
const image = new Image();
image.onload = () => {
images[imageName] = image;
resolve();
};
// add path to image directory. This path should be relative to your entry HTML file.
image.src = `./Images/${imageName}`;
});
}
Promise.all([downloadPromiseImage]).then(() => {
// do whatever with images dictionary
})
推荐阅读
- sql-server - 根据字段值从另一个表中选择数据
- google-apps-script - 如何使用 Google Apps 脚本在“Google Slide”中合并 2 个表格单元格
- javascript - 如何删除 Chart.js 中的标题颜色框
- javascript - JQuery:.find() 定位某些元素,但不定位其他元素
- android - 错误:在包“android”中找不到属性“appComponentFactory”的资源标识符
- python - Seaborn 分组箱线图 - 在每组对上方显示 P 值
- mocha.js - Mocha 重试不适用于 should.js 进行异步调用
- reactjs - useEffect 中的状态更新
- python - 无法将熊猫数据框写入配置单元表
- python - 使用 while 和 for 循环在 Python 中创建猜谜游戏