Centre sketch on specific X and Y co-ordinates


This is my first forum post/request so please forgive me if I miss any of the etiquette. I have used various various previous version of Java processing but am new to p5.js.

What I am struggling with is how to centre a sketch on a specific X and Y coordinate.
For example I have a sketch that is drawing on a 200,200 canvas, however the overall size of the sketch is 1000,1000. I have a circle that is moving around the canvas and who’s x/y co-ords are stored in a json object. What I am looking for is a way to have the centre of the sketch stay focused on the x/y co-ordinates of the of the circle.

I also have background objects and other objects that are moving around the co-ordinate system so need the co-ordinate system to remain intact and unaffected by the effects of keeping the view of the sketch being centered.

Thank you all very much for any help you can give me in my problem :slight_smile:


i think idea is to
translate to that circle center
or use this way.


At the top of draw, add:

translate(width/2.0, height/2.0); // center screen coordinates on 0,0
translate(-circleX, -circleY);    // put circle at 0,0

Or combine those into one command:

translate(width/2.0-circleX, height/2.0-circleY);


Given a canvas 1000,1000 and a circle at 123,456 – you want the circle to render at 500, 500.

So the offset is:

500-123 = 377
500-456 = 44

At the beginning of draw, you have translated by by 377,44. Now your coordinate system is intact, but your circle is drawing at the center (500,500). By intact, I mean that drawing at 123,456 is the center, while drawing 0, 456 is 123 pixels left of the center, et cetera – no need to push, pop, or translate back if you want your background objects in the same coordinate space.

Next frame the circle has moved – and the initial translate command re-centers the circle (and everything around it).

If you want some of background objects unaffected by the circle – say, a menu – you would isolate everything drawn the circle coordinate system with push/pop:

push / translate / draw circle and neighbors / pop / draw-menu


1 Like