xxxxxxxxxx
91
let img1, img2;
let shape1, shape2;
function preload() {
// Load images for the draggable objects
img1 = loadImage('image1.png');
img2 = loadImage('image2.png');
}
function setup() {
createCanvas(640, 360);
// Initialize the draggable objects
shape1 = new Draggable(50, 50, img1);
shape2 = new Draggable(250, 100, img2);
}
function draw() {
background(255);
// Check if the mouse is over the objects and update their position
shape1.over();
shape1.update();
shape1.show();
shape2.over();
shape2.update();
shape2.show();
}
function mousePressed() {
// Check if the mouse pressed the objects
shape1.pressed();
shape2.pressed();
}
function mouseReleased() {
// Release the dragged object
shape1.released();
shape2.released();
}
// Draggable class to handle image dragging
class Draggable {
constructor(x, y, img) {
this.x = x;
this.y = y;
this.img = img; // Store the image for this draggable object
this.w = img.width;
this.h = img.height;
this.dragging = false;
this.rollover = false;
}
over() {
// Is mouse over the object (the image)?
if (mouseX > this.x && mouseX < this.x + this.w && mouseY > this.y && mouseY < this.y + this.h) {
this.rollover = true;
} else {
this.rollover = false;
}
}
update() {
// Adjust location if being dragged
if (this.dragging) {
this.x = mouseX + this.offsetX;
this.y = mouseY + this.offsetY;
}
}
show() {
// Display the image at its current location
image(this.img, this.x, this.y);
}
pressed() {
// Check if the image was clicked
if (mouseX > this.x && mouseX < this.x + this.w && mouseY > this.y && mouseY < this.y + this.h) {
this.dragging = true;
// Keep track of the relative position within the object
this.offsetX = this.x - mouseX;
this.offsetY = this.y - mouseY;
}
}
released() {
// Stop dragging
this.dragging = false;
}
}