Reputation: 1186
I am trying to create an effect where you can hover over the webpage with your mouse and it will have a drawing and when you get to an area, you unveil an image. I thought about doing it this way:
How can I do this with p5.js?
I have it on my screen at the moment:
let img;
// function preload() {
// }
function setup() {
var canvas = createCanvas(
document.getElementById("myCanvas").offsetWidth,
document.getElementById("myCanvas").offsetHeight
);
canvas.parent("myCanvas");
// background(32);
loadImage("../img/monalisa.png", img => {
image(img, 0, 0);
});
}
function draw() {
// monaLisa();
rect(0, 0, 300, 300);
circles();
}
// function monaLisa() {
// image(img, 0, 0);
// }
function circles() {
// fill(255);
ellipse(mouseX, mouseY, 25, 25);
}
Upvotes: 3
Views: 780
Reputation: 11267
Simply push that rectangle to the right by such amount of pixels mouse is positioned from left side.
let img;
let edgeX = 0;
function setup() {
createCanvas(300,400)
img = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/300px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg")
}
function draw() {
// variable updates
if (mouseX > edgeX &&
mouseX >= 0 && mouseX <= 300 && // mouse within limits of picture
mouseY >= 0 && mouseY <= 400
) {
edgeX = mouseX;
}
// actual rawing
image(img, 0, 0);
fill('rgba(50,255,150, 0.5)');
rect(edgeX, 0, 300, 400);
}
If you want to uncover just a small segment of picture under the mouse position, then algo may be this:
Code:
let canvW = 300
let canvH = 400
let img
let dx = 20
let dy = 40
let diff = 3
let blocks
function setup() {
cursor(CROSS);
mouseX = -10;
mouseY = -10;
createCanvas(canvW,canvH)
img = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/300px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg")
blocks = new Array(canvH/dy);
for (var i=0; i < blocks.length; i++) {
blocks[i] = new Array(canvW/dx);
}
}
function draw() {
// variable updates
for (var y=0; y < blocks.length; y++) {
for (var x=0; x < blocks[y].length; x++) {
if (mouseX >= dx*x &&
mouseX <= dx*x+dx &&
mouseY >= dy*y &&
mouseY <= dy*y+dy
) {
blocks[y][x] = false;
}
}
}
// actual drawing
image(img, 0, 0)
stroke(70,127,240, 100)
strokeWeight(3)
for (var y=0; y < blocks.length; y++) {
for (var x=0; x < blocks[y].length; x++) {
if (blocks[y][x] !== false) {
// outer rectangle
fill(`rgba(50,127,240, 0.5)`)
rect(dx*x, dy*y, dx, dy)
// inner rectangle
fill(`rgba(70,127,240, 0.8)`)
rect(dx*x+diff, dy*y+diff, dx-2*diff, dy-2*diff)
}
}
}
}
Visuals: partly uncovered Mona Lisa if somebody is lazy to check demo:
Upvotes: 2