views:

574

answers:

3

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.

A: 

You can ask the user to calibrate the system, before use. It's not fully an answer to the question, but a sollution to the problem.

Just draw a red dot in the center of the screen, top left and bottem right. Ask the user to click on them, and retrieve the coordinates. Then, you know where the corners of the screen are.

Gerrit
+2  A: 

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.

Pim Jager
+3  A: 

Processing really isn't intended for creating webpages.. It's worse than Flash for sites (processing sketches being Java applets - Java being less common, far more resource-intensive and slow to load..)

That said, there is processing.js, a Javascript port of Processing.

The snake example accesses the mouse. Since it is Javascript, and the canvas is a div, the coordinates should be a bit more sane than Java (which lives in it's own VM world), but I could be wrong..

dbr