Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

323
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda