gpt4 book ai didi

javascript - 如何透视p5.js中的矩形?

转载 作者:行者123 更新时间:2023-11-30 06:14:16 29 4
gpt4 key购买 nike

我正在尝试创建一种效果,您可以将鼠标悬停在网页上,它会有一个绘图,当您到达某个区域时,您会看到一个图像。我考虑过这样做:

  • 在后面放一张图片
  • 在它上面有一个矩形(隐藏它)
  • 让一个元素(您的鼠标)能够越过矩形并删除鼠标悬停在其上的部分。

如何使用 p5.js 执行此操作?

现在我的屏幕上有它:

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

最佳答案

只需将该矩形向右推鼠标从左侧定位的像素数量即可。

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

p5 demo

编辑

如果你只想发现鼠标位置下的一小段图片,那么算法可能是这样的:

  1. 创建二维矩形数组
  2. 遍历矩形并将它们绘制在图像之上
  3. 如果鼠标与某个矩形相交 - 将其标记为不可绘制

代码:

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

p5 uncover segment demo

视觉效果:如果有人懒得看演示,部分露出蒙娜丽莎:

enter image description here

关于javascript - 如何透视p5.js中的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57192376/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com