How to convert screen coordinates to Cartesian coordinates?

Asked

Viewed 648 times

4

In Python: How to convert screen coordinates to cartesian coordinates, where there can be positive and negative points and the center of the screen is (0.0)?

  • would like to know if you tested my solution.

  • 2

    I gave it right, man, thanks!

1 answer

6


This is a coordinate system conversion problem and considering that its programming language originates from (0, 0) the upper left corner of the screen we have (in Javascript - in Python is analogous) :

<div style="width: 600px; height: 300px; border: 1px #000 solid; padding: 0px; margin: 0px;">


var larguraTela = 600;
var alturaTela = 300;
var getXY = function(x, y) {
    var novoX =  x - (larguraTela / 2);
    var novoY = (y - (alturaTela / 2)) * -1;
    return [ novoX, novoY ];
}

document.addEventListener('click', function(evt) {
    console.log(evt.x + ", " + evt.y);
    console.log(getXY(evt.x, evt.y));
}, false);

I did it in Java / HTML to test in the browser by clicking on the rectangle and observing the browser console, but what matters is the getXY() function that waits for the original X and Y coordinate as parameter and returns an array of two elements: x and y converted.

Note that it is necessary to multiply by (-1) in Y due to reverse direction in relation to the cartesian system traditional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.