1

I want to update each pixel to red, so this is my code

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

But the code seems doesn't work

hh54188
  • 14,887
  • 32
  • 113
  • 184

1 Answers1

3

The pixels array doesn't hold color values like that. The pixels array splits the colors into 4 separate indexes for red, green, blue, and alpha. From 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();

You might find it easier to work with the set() function, which takes x, y, and color parameters:

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();
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107