P5.js updatePixels()不起作用

时间:2017-12-26 00:44:26

标签: javascript p5.js

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

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()
}

但代码似乎不起作用

1 个答案:

答案 0 :(得分: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();
}