Search code examples
processingmouse-coordinates

Absolute mouse positions on Processing


(This is a copy paste of a post I made on the Processing forum, where I haven't got an answer so far. I 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

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?


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.