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

在p5.js中从上传图片加载像素?解决TypeError报错

解决p5.js中TypeError: img.loadPixels is not a function的问题

问题出在你混用了createImg()和loadImage()两个API:

  • createImg()返回的是DOM图像元素(p5.Element类型),这类对象只负责在页面上显示图片,没有loadPixels()这类像素操作方法。
  • 只有loadImage()创建的p5.Image对象才支持像素读取、修改等操作。

直接修改代码即可解决,核心是放弃createImg(),直接用loadImage()处理上传的文件:

修改后的完整代码

let imgInput, img;
let reds = [], greens = [], blues = [], alphas = [], newColor;
let tileSize = 20;

function setup() {
  createCanvas(400, 400);
  
  // 创建文件输入框
  imgInput = createFileInput(handleFile);
  imgInput.position(20, 20);
  imgInput.hide();
  
  // 创建开始按钮
  startBtn = createButton('Start Game');
  startBtn.position(width/2-startBtn.width/2, height/2 - startBtn.height/2);
  startBtn.mousePressed(start);
}

function draw() {
  if (img) {
    resizeCanvas(img.width, img.height);
    image(img, 0, 0, width, height);
  } else {
    background(255);
  }
}

function handleFile(file) {
  print(file);
  if (file.type === 'image') {
    // 直接用file.data作为loadImage的源,不需要createImg
    loadImage(file.data, storeImgValues);
  } else {
    img = null;
  }
  imgInput.hide();
}

// 接收loadImage返回的p5.Image对象
function storeImgValues(loadedImg) {
  // 把全局img赋值为p5.Image对象
  img = loadedImg;
  // 现在可以正常调用loadPixels()
  img.loadPixels();
  
  console.log('hi')
  
  let pixel = 0;
  for (let l = 0; l < img.pixels.length; l += 4) {
    reds[pixel] = img.pixels[l];
    greens[pixel] = img.pixels[l+1];
    blues[pixel] = img.pixels[l+2];
    alphas[pixel] = img.pixels[l+3];
    pixel++; // 补上索引递增,避免所有值存在数组同一位
  }
}

function start() {
  startBtn.hide();
  imgInput.show();
}

关键修改点说明

  1. 移除createImg()调用:上传的文件数据file.data可以直接传给loadImage(),不需要先转成DOM元素。
  2. 回调函数接收p5.Image对象:loadImage()的成功回调会把加载好的p5.Image作为参数传入,直接用这个对象进行像素操作。
  3. 修复像素数组索引递增:原代码里pixel变量没有递增,会导致所有颜色值都存在数组的第0位,现在补上pixel++。

这样修改后,你就能正常读取图像的像素数据,不会再出现loadPixels is not a function的错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:45:30