Translating everything/ moving on the canvas

Hi,
I want to move over my canvas by clicking and dragging. With the code below, the rect is getting reinstatiated every time the mouse is clicked. How can I change the code, so the rect is being translated from its new position and does not spawn at its original position?


let bx;
let by;

let posMouseX;
let posMouseY;

function setup() {
    let myCanvas = createCanvas(1000, 1000);
    myCanvas.parent('myContainer');
}

function draw() {
    background(255);
    translate(bx, by);
    rect(width/2, height/2, 20, 20);
}

function mousePressed(){
    posMouseX = mouseX;
    posMouseY = mouseY;
}

function mouseDragged() {
    bx = mouseX - posMouseX;
    by = mouseY - posMouseY;
}
1 Like

I was going to say that it won’t be simple, but the I tried your code and realized what you were trying to do. Problem was in fixing posMouseX when you are really interested in change of coordinates (i.e. dragging). Anyway if you replace with this code it works as you intended.

function mousePressed(){
    oldMouseX = mouseX;
    oldMouseY = mouseY;
}

function mouseDragged() {
    newMouseX = mouseX;
    newMouseY = mouseY;
    bx -= oldMouseX - newMouseX;
    by -= oldMouseY - newMouseY;
    oldMouseX = newMouseX;
    oldMouseY = newMouseY;
}
2 Likes