【问题标题】:loading images from local folder instead of website in .js从本地文件夹而不是 .js 中的网站加载图像
【发布时间】:2023-03-20 15:49:01
【问题描述】:

我对编码非常陌生,尤其是 .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>

【问题讨论】:

    标签: javascript image for-loop loadimage


    【解决方案1】:

    这将为您提供一个带有键和与之对应的图像的字典。 例如,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
    })
    

    【讨论】:

    • 非常感谢!但我不知道我是否能得到它……它要复杂得多。我会尝试!我应该在预加载之前还是在预加载中添加这个?
    • 我只是确保在开始渲染之前下载图像。我会将 Promise.all([downloadPromiseImage]).then(() => {//your setup code here} 放在你的设置函数中并删除预加载。
    • 我终究无法得到它。但我会回到它,需要一些练习!非常感谢
    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 2017-10-08
    • 2018-02-20
    相关资源
    最近更新 更多