How to get the real position were a point is drawn after translate and rotate in P5JS

325 Views Asked by At

I read a lot, and tried many things, but can't get this done, and it seems simple

I have the following p5js code

function setup() {
  let canvas = createCanvas(400, 400);
  noLoop();
}

function draw() {
  background(220);

  push();
  translate(50,100);
  point(25,25);
  // MISSING CODE to get 75,125
  pop();
  
} 

And I'm trying to figure out if there is a way to get the actual coordinates were the point is drawn, I read about getTransform, the matrix, and a lot of stuff, but seems impossible to get it done. Also I need to use rotation in the transform, so that makes it even harder

Thanks!

2

There are 2 best solutions below

3
AudioBubble On

Use variables, so you can keep track of how much you translated and the location of your point, so you can them add them to obtain the desired result.

let trans_x = 50
let trans_y = 100
let point_x = 25
let point_y = 25


translate(trans_x, trans_y);
point(point_x, point_y);

result_x = trans_x + point_x  // 50+25=75
result_y = trans_y + point_y  // 100+25=125

You could use Vectors so you don't have to define 2 variables, but you get the idea.

Usually you would call WorldPosition to the absolute position of the object and RelativePosition to the position the object relative to the CameraPosition

The translation would be called CameraPosition and to make your code more efficient you should only draw objects that their RelativePosition falls inside the drawable area.

0
Ouss On

You can do some transformation matrix magic:

  const ctx = drawingContext; // Alias for this._renderer.drawingContext
  const matrix = ctx.getTransform(); // This is a DOMMatrix in web browsers that support it
  // for the 2D case:
  const rot = atan2(matrix.b, matrix.a);
  console.log(rot); // the answer is in Radians if I am not mistaken
  const scale_x = sqrt(matrix.a**2 + matrix.c**2);
  const scale_y = sqrt(matrix.b**2 + matrix.d**2);
  const pos = createVector(matrix.e/scale_x, matrix.f/scale_y); // check pos.x and pos.y
  console.log(pos);