mike239x
mike239x

Reputation: 215

How to clear part of the buffered image with p5.js

I am using javascript with p5.js framework. I created an offscreen graphics buffer. Now I want to clear part of that buffer (so it becomes invisible again). What is the best way to do it?

Right now I can only achieve that by direct changing of the alpha value for every pixel I need.

Here is a MCVE:

// sketch.js, requires p5.js

function setup() {
  createCanvas(100,100);
  background(0);
  let mymap = createGraphics(100,100);
  mymap.fill(255);
  mymap.rect(20,20,40,40);
  mymap.loadPixels();
  for (let i = 23; i < 37; i++) {
    for (let j = 23; j < 37; j++) {
      mymap.pixels[400*i+4*j+3] = 0;
    }
  }
  mymap.updatePixels();
  image(mymap,0,0);
}

Some side-notes:

1) there is a tiledmap.js library to p5.js, but I am still reading into it's source code and right now it doesn't look like they got 1 buffer for the entire tilemap.

2) there is a clear function to clear the canvas graphics, it does clear things, but it clears everything on the given buffer.

Upvotes: 1

Views: 1443

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

You should be able to use the set() function. More info can be found in the reference.

I would expect something like this to work:

const transparency = createGraphics(20, 20);
mymap.set(30, 30, transparency);
mymap.updatePixels();

Unfortunately, this seems to only set a single pixel. This smells like a bug to me, so I've filed this bug on GitHub.

Like you've discovered, you can also set the pixel values directly. This might be simpler than what you currently have:

let mymap;

function setup() {
  createCanvas(100,100);
  mymap = createGraphics(100,100);
  mymap.fill(255, 0, 0);
  mymap.rect(20,20,40,40);

    for(let y = 30; y < 50; y++){
        for(let x = 30; x < 50; x++){
            mymap.set(x, y, color(0, 0, 0, 0));
        }
    }

    mymap.updatePixels();
}

function draw() {
  background(0, 255, 0);
  image(mymap,0,0);
}

Note that there's a tradeoff: this code is simpler, but it's also slower.

Upvotes: 1

Related Questions