Please help with set() and get()

Hello good people,

I have been writing code to manipulate an image in p5.js. The effect that I want to achieve is simple. But I can’t get around to find a way to do it. Currently, the result from my code is that the image on the left is slowly replaced by an image on the right in a random position.

This is my code:

But actually, what I want to achieve is to make the image on the left cover-up by image on the right but then it would go back to the original image in a random position. So the effect would be like never-ending interchangeable between two images. (Did I make sense? :sweat_smile:)

Any idea? Thank you so much for any suggestion :slightly_smiling_face:

please format code with </> button * homework policy * asking questions

1 Like

You could set the pixels of a createGraphics() so that you are able to easily transition the image back to default. As is, you are setting the pixels of the image so there is no way of getting that original pixel data back, unless you cache it off on run.

here is an example to get you going … i am using setInterval() to toggle a boolean that determines which pixels to get. Then in draw just check the state of that boolean and set pixels accordingly.

let img,
  g,
  toggleImageToDraw = false;

function preload() {
  img = loadImage('potrait.png');
}

function setup() {
  createCanvas(1000, 500);
  g = createGraphics(500, 500);
  setInterval(_ => {
    toggleImageToDraw = !toggleImageToDraw;
  }, 10000);
}


function draw() {
  let x1 = random(0, 300);
  let y1 = random(0, height);

  let x2 = x1 + 500;
  let w = 200;
  let h = height / 100;

  if (!toggleImageToDraw) {
    g.set(x1, y1, img.get(x2, y1, w, h));
  } else {
    g.set(x1, y1, img.get(x1, y1, w, h));
  }

  image(g, 0, 0);
}
2 Likes

Ohhhh!! Thank you for your suggestion to use createGraphic(). I can see this would solve the problem.

Anyway, your solutions is really good too, but I am bit confuse with the setInterval() Would you mind to explain to me this line code:

 setInterval(_ => {
    toggleImageToDraw = !toggleImageToDraw;
  }, 10000);
2 Likes

I am using setInterval() to toggle my boolean toggleImageToDraw every 10 seconds …

setInterval() calls a function every so many specified milliseconds …

https://www.w3schools.com/jsref/met_win_setinterval.asp
https://www.w3schools.com/js/js_arrow_function.asp

2 Likes