尝试在 p5.js 草图中调整窗口(矩形)的大小,以达到与我演示的类似的结果。完整的 p5.js 项目可以在这里获得。希望有人可以提供帮助,请记住我无论如何都不是开发人员,而是在努力学习。预先感谢。
contains(x, y) {
return x > this.x - this.w/2 && x < this.x + this.w/2 &&
y > this.y - this.h/2 && y < this.y + this.h/2;
}
resize(mouseX, mouseY) {
const margin = this.w * this.resizeThreshold;
if (dist(mouseX, mouseY, this.x + this.w / 2, this.y + this.h / 2) < margin) {
this.resizeOriginX = mouseX;
this.resizeOriginY = mouseY;
this.isResizing = true;
} else {
this.isResizing = false;
}
}
}
let windows = [];
let selectedWindow = null;
// Event handlers
function mousePressed() {
for (let i = windows.length - 1; i >= 0; i--) {
windows[i].resize(mouseX, mouseY);
if (windows[i].contains(mouseX, mouseY)) {
selectedWindow = windows[i];
windows.splice(windows.indexOf(selectedWindow), 1);
windows.push(selectedWindow);
return;
}
}
selectedWindow = null;
}
function mouseDragged() {
if (selectedWindow) {
if (!selectedWindow.isResizing) {
selectedWindow.x = mouseX;
selectedWindow.y = mouseY;
} else {
const newWidth = mouseX - selectedWindow.resizeOriginX;
const newHeight = mouseY - selectedWindow.resizeOriginY;
print(`newWidth = ${mouseX} + ${selectedWindow.resizeOriginX}`);
print(`newWidth = ${mouseY} + ${selectedWindow.resizeOriginY}`);
selectedWindow.w = newWidth;
selectedWindow.h = newHeight;
}
}
}
function mouseReleased() {
if (selectedWindow) {
selectedWindow.isResizing = false;
selectedWindow = null;
}
}
以下源代码展示了如何移动矩形并调整其大小:
let r;
let xOffset = 0.0;
let yOffset = 0.0;
var selected = false;
var inGrabber = false;
class Rect {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
display() {
rect(this.x, this.y, this.w, this.h);
if (selected) { // show the grabber rect if its selected
rect(this.x + this.w - 5, this.y + this.h - 5, 10, 10);
}
}
}
function setup() {
createCanvas(800, 600);
r = new Rect(100, 100, 200, 100);
}
function draw() {
background(220);
r.display();
}
function mousePressed() {
if (
mouseX >= r.x &&
mouseX <= r.x + r.w &&
mouseY >= r.y &&
mouseY <= r.y + r.h
) {
selected = true;
console.log("selected");
xOffset = mouseX - r.x;
yOffset = mouseY - r.y;
cursor(HAND);
} else {
selected = false;
}
if (
mouseX >= r.x + r.w - 5 &&
mouseX <= r.x + r.w + 5 &&
mouseY >= r.y + r.h - 5 &&
mouseY <= r.y + r.h + 5
) {
console.log("in grabber");
inGrabber = true;
} else {
inGrabber = false;
}
}
function mouseDragged() {
console.log("dragged");
if (selected) {
r.x = mouseX - xOffset;
r.y = mouseY - yOffset;
}
if (inGrabber) {
r.w = mouseX - r.x;
r.h = mouseY - r.y;
}
}
function mouseReleased() {
console.log("released");
cursor(ARROW);
}