# Translating everything/ moving on the canvas

**URL:** https://discourse.processing.org/t/translating-everything-moving-on-the-canvas/23409
**Category:** Coding Questions
**Created:** [August 21, 2020, 6:57am UTC](https://discourse.processing.org/t/translating-everything-moving-on-the-canvas/23409 "2020-08-21T06:57:20Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Luis\_Luethi1](https://avatars.discourse-cdn.com/v4/letter/l/5f8ce5/32.png) [@Luis\_Luethi1](https://discourse.processing.org/u/Luis_Luethi1)
#### Post date: [August 21, 2020, 6:57am UTC](https://discourse.processing.org/t/translating-everything-moving-on-the-canvas/23409/1 "2020-08-21T06:57:20Z")

</div>

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?

```auto

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;
}

```

---

<div class="post-metadata">

### Author: ![SomeOne](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/someone/32/8639_2.png) [@SomeOne](https://discourse.processing.org/u/SomeOne)
#### Post date: [August 21, 2020, 9:19am UTC](https://discourse.processing.org/t/translating-everything-moving-on-the-canvas/23409/2 "2020-08-21T09:19:48Z")

</div>

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.

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

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

```
