简体   繁体   中英

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

The following code should set the color value of each pixel of the createGraphics object to red, but only thing that is rendered is the gray background.

 ////////////////////////////////////////////////////////// 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); }

The main issue with your code is that you are not setting an alpha value. By leaving the alpha equal to zero the changes to the graphics object are transparent.

Here is similar code that sets the alpha value to 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM