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