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



下面的代码应该将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>

最新更新