13

I want to achieve something like an infinite drag like the one in Konva js Can anyone help me with this. I try varius things but non of them were ok. Im new in p5js and javascript. Please for any hints. Only this element prevents me from completing the entire project.

var grid;
var current_img;
var BgCat1 = [];
var layerOne;
let show_grid = false;

Michael
  • 168
  • 2
  • 18

1 Answers1

11

There may be a more elegant solution, but here I draw an extra cell on each side of the grid to handle the wraparound, so a 12x12 grid with 10x10 visible. See it run here: https://editor.p5js.org/rednoyz/full/uJCADfZXv

let dim = 10, sz;
let xoff = 0, yoff = 0;

function setup() {
  createCanvas(400, 400);
  sz = width/ dim;
}

function mouseDragged() {
  xoff += mouseX - pmouseX;
  yoff += mouseY - pmouseY;
}

function draw() {
  background(255);

  for (let i = 0; i < dim+2; i++) {
    for (let j = 0; j < dim+2; j++) {

      let x = ((xoff + j * sz) % (width+sz)) - sz;
      if (x < -sz) x += width+sz;

      let y = ((yoff + i * sz) % (height+sz)) - sz;
      if (y < -sz) y += height+sz;

      rect(x, y, sz, sz);
      text(i * 10 + j, x + sz/2, y + sz/2);
    }
  }
}
rednoyz
  • 1,318
  • 10
  • 24
  • You can also put `if((mouseX < width && mouseX > 0)&&(mouseY < height && mouseY > 0))` on `mouseDragged()` function to work only on canvas dragging – darcane Nov 22 '19 at 13:28
  • anything else you are looking for in this answer, @michał-mi ? – rednoyz Nov 26 '19 at 17:28
  • I was responding to the questioner's request for additional code, which was later deleted – rednoyz Nov 28 '19 at 05:17