有没有办法在 createGraphics() 对象中获取和设置像素颜色值?

Is there any way to get and set pixel color values in a createGraphics() object?

所以我知道如何使用 loadPixels() 和 updatePixels() 来改变主要 canvas 的单个像素,就好像它是位图一样。是否有任何类似的技术来访问 createGraphics() 对象的像素?或者我是否必须将它写入 canvas 然后对其进行操作?

或者我应该以某种方式使用 drawingContext 对象吗?

如果你想操纵像素使用createImage()

如果您想使用图形函数轻松绘图,请使用 createGraphics()loadPixels() / 阅读 pixels[] 应该可行:

var buffer;

function setup() {
  createCanvas(400, 400);
  
  buffer = createGraphics(10,10);
  buffer.ellipse(5,5,5);
  buffer.loadPixels();
  console.log(buffer.pixels);
}

function draw() {
  background(220);
  image(buffer,0,0,400,400);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

如果需要,您当然也可以将像素写入 PGraphics。 如果您不需要绘图功能而只需要像素,PImage 会更轻一些。

这是一个例子:

var buffer;
  
function draw() {
  background(220);
  image(buffer,0,0,400,400);
}

function setup() {
  createCanvas(400, 400);
  buffer = createGraphics(10,10);
  buffer.ellipse(5,5,5);
  buffer.loadPixels();
  // print pixels (list of bytes in order (e.g. [r0,g0,b0,a0,r1,g1,b1,a1,...])
  console.log(buffer.pixels);
  
  var gradientW = 3;
  var gradientH = 3;
  for(var y = 0; y < gradientH; y++){
    for(var x = 0; x < gradientH; x++){
      // calculate 1D index from x,y
      let pixelIndex = x + (y * buffer.width);
      // note that as opposed to Processing Java, p5.Image is RGBA (has 4 colour channels, hence the 4 bellow)
      // and the pixels[] array is equal to width * height * 4 (colour cannels)
      // therefore the index is also * 4
      let rIndex = pixelIndex * 4;
      
      console.log('x',x,'y',y,'pixelIndex',pixelIndex,'red index',rIndex);
      // access and assign red
      buffer.pixels[rIndex]     = round(map(x,0,3,0,255));
      // access and assign green
      buffer.pixels[rIndex + 1] = round(map(y,0,3,0,255));
      // access and assign blue
      buffer.pixels[rIndex + 2] = 255 - buffer.pixels[rIndex] + buffer.pixels[rIndex + 1] 
      // access and assign alpha
      buffer.pixels[rIndex + 3] = 255;
      
    }
  }
  
  buffer.updatePixels();
}

function draw() {
  background(220);
  image(buffer,0,0,width,height);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>