绘制到 p5.Image 而不是 canvas

Drawing to p5.Image instead of to canvas

给定一个加载的 png 图像作为模板,我想让用户能够跟踪图像的元素。在 p5 中,这很容易:

setup() {
    // Load image
    var img = loadImage('...');
    image(img, 0, 0);
}

draw() {
    ellipse(mouseX, mouseY, 2, 2);
}

但是,我希望能够 保存省略号(没有底层图像)。有没有一种方法可以写入 Image 而不是直接写入 canvas,这样我就可以在不使用原始图像的情况下提升轨迹的像素?

我目前的计划是:

警告:图像是 p5.Image,因此叠加在 <img> 上是不够的。

您可以使用 createGraphics() 函数创建 p5.Renderer 的实例。然后,您可以绘制到 p5.Renderer,然后将其覆盖在图像之上。然后您可以访问 p5.Renderer 的像素数组以仅获取叠加层,而不是图像。

这是一个例子:

var img;
    var pg;
    
    function preload() {
      img = loadImage("https://www.gravatar.com/avatar/06ce4c0f7ee07cf79c81ac6602f5d502?s=32&d=identicon&r=PG");
    }
    
    function setup(){
      createCanvas(300, 600);
      pg = createGraphics(300, 300);
    }
    
    function mousePressed(){
      pg.fill(255, 0, 0);
      pg.ellipse(mouseX, mouseY, 20, 20);
    }
    
    function draw() {
      image(img, 0, 0, 300, 300);
      image(pg, 0, 0);
      image(pg, 0, 300);
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.0/p5.js"></script>
Click in the image to draw to the buffer below it! (View as full page to see the buffer.)

可以在 the reference 中找到更多信息。

顺便说一句,有一个 标签。