Normalize and center coordinate system

In my drawings, I’d like to set the xy axis centred in the middle of the screen and rescaled between -0.5 and 0.5 instead of using screen coordinates. That makes the drawing independent of screen resolution.

I tried:

function draw() {
     background(255);
     let _ratio = windowWidth / windowHeight;
     let _scale; 
     // keep aspect ratio and use centre square of the screen.
     if (_ratio >= 1.0) {
        _scale = windowHeight;
     } else {
        _scale = windowWidth;
     }
     // translate to the centre of the screen
     translate(windowWidth / 2, windowHeight / 2);
     // scale coordinate system between 
     scale(_scale);
     line(-0.5, 0, 0.5, 0);    // x-axis
     line(0, -0.5, 0, 0.5);    // y-axis
}

Now all strokes are scaled as well. How can I normalise the coordinate system only without rescaling the strokes?

I know I can use map function to recalculate every coordinate, but that makes the code rather long if I have to remap every coordinate before calling a draw function.

Hello,

Consider using vectors for your (x,y) co-ordinates.
You can then scale these as you wish.

References:
https://p5js.org/reference/#/p5.Vector

There is a learning curve to this but worth it in the end.

If you use WEBGL it will automatically put the origin at the center of the screen:
https://p5js.org/reference/#/p5/createCanvas

And you can go 3D with those vectors!

:)

Probably the easiest way is to set the stroke weight based on _scale i.e. something like

strokeWeight(1.0 / _scale);

should work. You might need to change the 1.0 to represent the stroke weight required when
_scale = 1

2 Likes

That works! Thank you.

1 Like