Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

322
Views
How to move the image inside rectangle in p5js?

I'm currently doing a project regarding p5.js and I need to do the following:

Input: given image and rectangle;

Algorithm: move the image inside the rectangle. By saying moving, I mean when the mouse is clicked, move the whole image to match the size of the rectangle by showing an only portion of the image (size of the rectangle)

Output: dragging image inside the rectangle

My current code is moving the image, but I need an image to be inside the rectangle and show only part of the image that is this size of the rectangle. The code is written in React:

  let backgroundImage;
  let dragging = false; 
  let rollover = false; 

  let x, y, w, h; // Location and size
  let offsetX, offsetY; 
  const preload = (p5) => {
    const url =
      "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/640px-Image_created_with_a_mobile_phone.png";
    backgroundImage = p5.loadImage(url);
  };

  const setup = (p5, parentRef) => {
    p5.createCanvas(1000, 500).parent(parentRef);
    // Starting location
    x = 100;
    y = 100;

    // Dimensions
    w = 300;
    h = 400;
  };

  const draw = (p5) => {
    p5.background(233);
    if (
      p5.mouseX > x &&
      p5.mouseX < x + w &&
      p5.mouseY > y &&
      p5.mouseY < y + h
    ) {
      rollover = true;
    } else {
      rollover = false;
    }
    if (dragging) {
      x = p5.mouseX + offsetX;
      y = p5.mouseY + offsetY;
    }

    p5.image(backgroundImage, x, y, w, h);
    p5.noFill();
    p5.rect(400, 100, 200, 300);
  };

  const mousePressed = (p5) => {
    if (
      p5.mouseX > x &&
      p5.mouseX < x + w &&
      p5.mouseY > y &&
      p5.mouseY < y + h
    ) {
      dragging = true;

      offsetX = x - p5.mouseX;
      offsetY = y - p5.mouseY;
    }
  };

  const mouseReleased = (p5) => {
    dragging = false;
  };

to display it, I use following code:

<Sketch
          preload={preload}
          setup={setup}
          draw={draw}
          mouseReleased={mouseReleased}
          mousePressed={mousePressed}
        />

I use react-p5 library.

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!