R – Absolute Mouse Positions on Processing

mouse-coordinatesprocessing

This is a copy paste of a post i made on the processing forum (where i haven't got an answer so far) thought i might as well try here.

Processing is a very cool way to draw stuff, specially for the webpages. Just as a reference http://processing.org

Hey, i'm new to processing, i'm using it to make a flashless website, so i'm pretty much drawing on a canvas.

I'm having a problem with the mouse position, although the coordinates, when drawing, consider the top left corner to be position 0,0; the actual mouse coordinates consider the 0,0 to be the top left corner of the browser window.

So my problem is this, the canvas is operating on a centered web-page, whenever the browser changes size, so does the coordinates of the mouse within the canvas.

Is there any way to make the coordinates of the mouse relative to the canvas? So that i can change the size of my browser window and the top left corner will be always 0,0 for the mouse coordinates?

So that's the problem, i dunno how many ppl here in stackoverflow are experienced with this, but i hope someone could help me 🙂

thanks to the stack overflow community in advance.

Best Solution

I'm not familiar with processing, but can't you just calculate the difference between the top left corner of the browser window and the top left corner of the canvas?
i.e. (using jquery)

$(window).onresize = function() {
 //offset return position realive to the document.
 var offset = $('#canvas').offset();
 window.canvasLeft = offset.left;
 window.canvasTop = offset.top;
}

Then you can do something like:

 relativeMouseLeftPosition = mouseLeftPosition() - window.canvasLeft;

You should replace #canvas with a css selector for your canvas area.

Also note that window is the global object, I use it here to deal with possible scope problems.

Related Question