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

P5加载CSV表格及图片失败,报错无法读取undefined的gifProperties属性

问题根因

你遇到的报错本质是P5.js在WEBGL模式下尝试将未完成加载/不存在的图片对象绑定为纹理,结合你仅当前CSV出错的现象,具体触发原因有两类:

  1. 你硬编码了固定渲染数量num = 45,如果当前CSV的key列总条数不足45,循环到超出实际数组长度的索引时,studentImages[i]取值为undefined,渲染时就会触发属性读取报错
  2. 当前CSV中部分key值对应的图片路径不存在,loadImage执行后返回的是无效图片对象,调用纹理方法时识别失败

修复步骤

  • 首先移除硬编码的固定数量,直接用CSV实际返回的有效图片数作为渲染上限,避免数组越界:
// 删掉顶部的let num = 45定义
function setup() {
  let studentImages = processCSV(table)
  // 新增校验,确认CSV读取结果
  console.log('当前CSV key列总条数:', studentImages.length)
  createCanvas(windowWidth, windowHeight, WEBGL);
  colorMode(HSB, 360, 100, 100, 100);
  // 直接用实际返回的图片数循环
  for (let i = 0; i < studentImages.length; i++) {
    // 新增判断,仅有效图片对象进入渲染队列
    if(studentImages[i] && studentImages[i].width > 0) {
      let x = random(-width , width);
      let y = random(-height, height);
      let z = random(-width*5, width);
      let texture = new Type(studentImages[i], x, y, z)
      imgs_arr.push(texture);
    }
  }
}
  • 给loadImage加错误回调,处理路径不存在的异常,避免无效对象进入数组:
function processCSV(csv) {
  let imgLinks = [];
  csv.getColumn('key').forEach((e,i) => {
    let link = `./projects/2021/${e}/${e}-project.jpg`
    imgLinks[i] = loadImage(
      link,
      () => console.log(`加载成功:${link}`),
      () => {
        console.log(`加载失败:${link}`)
        // 可选:加载失败时替换为占位图,避免缺项
        // imgLinks[i] = 你提前加载好的默认占位图对象
      }
    )
  }); 
  return imgLinks
}
  • 优化渲染逻辑,避免性能问题和兼容问题:
    1. 不要在draw循环里执行resize操作,该操作会反复修改图片尺寸引发性能损耗,放到Type类的构造函数里仅执行一次
    2. WEBGL模式下绑定纹理后建议用plane()绘制带纹理的平面,比image()方法兼容性更好,修改display方法:
class Type {
  constructor(_img, _x, _y, _z) {
    this.img = _img;
    this.x = _x;
    this.y = _y;
    this.z = _z;
    // 构造时一次性调整尺寸
    if (window.screen.width < 767) {
      this.img.resize(100,100)
    }
    this.w = this.img.width
    this.h = this.img.height
  }

  update() {
    this.z += 5;
    if(this.z > width/2){
      this.z = -width*5;
    }
  }

  display() {
    push();
    translate(this.x, this.y, this.z);
    texture(this.img)
    // 用plane绘制纹理
    plane(this.w, this.h)
    pop();
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:30:02