xxxxxxxxxx
92
// Time Displacement Slitscan
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/challenges/164-time-slitscan.html
// Ported to p5.js by Loïc Bertrand
let sourceType = "IMAGE"; // "WEBCAM" or "IMAGE"
let source; // camera or image
let sourceImg; // used when sourceType === "IMAGE"
let imgMotionRadio; // used when sourceType === "IMAGE"
let sourceButton;
const IMG_MOTION_SINEWAVE = "IMG_MOTION_SINEWAVE";
const IMG_MOTION_MOUSE = "IMG_MOTION_MOUSE";
const H = 8; // slice height
const WIDTH = 480;
const HEIGHT = 360;
let history;
let historyIndex = 0;
let offset = 0;
function changeSourceType(sourceTypeParam) {
sourceType = sourceTypeParam;
sourceButton.html(sourceType === "IMAGE" ? "Use webcam" : "Use image");
if (sourceType === "IMAGE") {
source = createGraphics(WIDTH, HEIGHT);
sourceImg = loadImage("dog_helena_lopes_pexels.png");
sourceImg.resize(WIDTH, HEIGHT);
} else if (sourceType === "WEBCAM") {
source = createCapture(VIDEO);
source.hide();
}
}
function setup() {
createCanvas(WIDTH, HEIGHT);
imgMotionRadio = createRadio();
imgMotionRadio.option(IMG_MOTION_SINEWAVE, "Sinewave motion");
imgMotionRadio.option(IMG_MOTION_MOUSE, "Move with the mouse");
imgMotionRadio.selected(IMG_MOTION_SINEWAVE);
sourceButton = createButton("");
sourceButton.mousePressed(() => {
changeSourceType(sourceType === "IMAGE" ? "WEBCAM" : "IMAGE");
});
changeSourceType(sourceType);
history = Array.from({ length: floor(height / H) });
for (let i = 0; i < history.length; i++) {
history[i] = createImage(width, height);
}
background(0);
}
function draw() {
if (sourceType === "IMAGE") {
imgMotionRadio.show();
const xOffset =
imgMotionRadio.value() === IMG_MOTION_SINEWAVE
? sin(frameCount * 0.2) * 20
: map(mouseX, 0, width, -1, 1) * 20;
source.image(sourceImg, xOffset, 0, width, height);
} else {
imgMotionRadio.hide();
}
for (let i = 0; i < history.length; i++) {
const y = i * H;
const currentIndex = (i + offset) % history.length;
copy(history[currentIndex], 0, y, width, H, 0, y, width, H);
}
offset++;
history[historyIndex].copy(
source,
0,
0,
source.width,
source.height,
0,
0,
width,
height
);
historyIndex = (historyIndex + 1) % history.length;
}