P5.js updatePixels()不起作用

问题描述 投票:1回答:1

我想将每个像素更新为红色,所以这是我的代码

const canvasWidth = 800
const canvasHeight = 600

function setup() {
  createCanvas(canvasWidth, canvasHeight)
  loadPixels()
  let xoff = 0
  for (let x = 0; x < canvasWidth; x++) {
    let yoff = 0
    for (let y = 0; y < canvasHeight; y++) {
      pixels[x + y * canvasWidth] = color('red')
      yoff += + 0.01;
    }
    xoff += 0.01
  }
  updatePixels()
}

但代码似乎不起作用

javascript p5.js
1个回答
2
投票

pixels数组不保存这样的颜色值。 pixels数组将颜色分为4个单独的索引,分别为红色,绿色,蓝色和alpha。来自the reference

var pink = color(255, 102, 204);
loadPixels();
var d = pixelDensity();
var halfImage = 4 * (width * d) * (height / 2 * d);
for (var i = 0; i < halfImage; i += 4) {
  pixels[i] = red(pink);
  pixels[i + 1] = green(pink);
  pixels[i + 2] = blue(pink);
  pixels[i + 3] = alpha(pink);
}
updatePixels();

你可能会发现使用set()函数更容易,它需要xycolor参数:

const canvasWidth = 800
const canvasHeight = 600

function setup(){
    createCanvas(canvasWidth, canvasHeight);
    loadPixels();
    for (let x = 0; x < canvasWidth; x++) {
        for (let y = 0; y < canvasHeight; y++) {
            set(x, y, color('red'));
        }
    }
    updatePixels();
}
© www.soinside.com 2019 - 2024. All rights reserved.