Search code examples
typescriptp5.js

How to write text on the right side in an inverted geometric reference frame with p5


In p5, axis y points downwards. This code make it point upwads (and make the 0,0 the center)

type gridRange={
    xrange:{
        min: number,
        max: number,
    },
    yrange:{
        min: number,
        max: number,
    }
};



const setCoordinateSystem =(r :gridRange,p : p5) =>{
    let xscalingCoeff = window.innerWidth / (r.xrange.max - r.xrange.min);
    let yscalingCoeff = window.innerHeight / (r.yrange.max - r.yrange.min) * -1; // MAKE y points upwards
    let xcenter = r.xrange.max ;
    let ycenter = r.xrange.min ; //NOT AN ERROR!
    p.scale(xscalingCoeff, yscalingCoeff);
    p.translate(xcenter, ycenter);

};


function draw(p: p5): void {
  p.background(255)

 const r: gridRange = {
        xrange: {
            min: -25,
            max: 25,
        },
        yrange: {
            min: -25,
            max: 25,
        },
    };

    setCoordinateSystem(r,p)
}

It works I have a frame with x between -25 and 25, y between -25 and 25 with x and y pointing rightwards and upwards respectively.

But when I add in draw code to write a text.

  p.text('test', -25, 0); 

rhe text in inverted. How can fix this problem.

The proposed solution from Thuong Vo works (probably I haven't tried it) but because I have a lot things to print I don't want call a function changing the coordinate of my objects every time. I want to change the coordinate systems one time only.

enter image description here


Solution

  • lot of code for nothing but at least it works

    import p5 from "p5";
    
    export const print = (p :p5, txt: string,wherex: number, wherey :number) => {
        p.scale(1, -1);
        p.textSize(10);
        p.text(txt, wherex, wherey);
        p.scale(1, -1);
    }
    

    or even better

    import p5 from "p5";
    
    export const print = (p :p5, txt: string,wherex: number, wherey :number) => {
        p.push();
        p.scale(1, -1);
        p.textSize(10);
        p.text(txt, wherex, wherey);
        p.pop();
    }
    

    and use

       print(p,"test",x,y)
    

    instead of

       p.text("test", x, y);