P5.js / 如何在 createGraphics 对象的每个像素上设置颜色值

P5.js / how to set a color value on each pixel of createGraphics object

以下代码应将 createGraphics 对象的每个像素的颜色值设置为红色,但只呈现灰色背景。

//////////////////////////////////////////////////////////
function setup() {
    createCanvas(800, 600);
    pixelDensity(1);
    gp = createGraphics(width, height);
     
}
//////////////////////////////////////////////////////////
function draw() {
    background(125);
    gp.loadPixels();
    for(var x = 0; x < width; x++){
         for(var y = 0; y < height; y++){
           var index = (width * y + x) * 4;
           gp.pixels[index+0]= 255;
           gp.pixels[index+1]= 0;
           gp.pixels[index+2]= 0;   
         }  
      }
      gp.updatePixels();
      image(gp,0,0, width,height);   
}

您的代码的主要问题是您没有设置 alpha 值。通过将 alpha 保留为零,对图形对象的更改是透明的。

这里是将 alpha 值设置为 100 的类似代码。

var gp;
function setup() {
    createCanvas(800, 600);
    pixelDensity(1);
    gp = createGraphics(width, height);
    gp.pixelDensity(1);
    noLoop(); 
}

function draw() {
    background(255)
    gp.loadPixels();
    for(var x = 0; x < width; x++){
         for(var y = 0; y < height; y++){
           var index = (width * y + x) * 4;
           gp.pixels[index+0]= 255.0;
           gp.pixels[index+1]= 0;
           gp.pixels[index+2]= 0;
           gp.pixels[index+3]= 100.0;   
         }  
      }
      gp.updatePixels();
      image(gp,0,0, width,height);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>