4

I have a canvas with 100% width and height.

It is part of a remote desktop I am working on. Currently I am stuck because the mouse position does not reflect the position on the canvas correctly.

When I send the data to the desktop I have to compensate for different screen sizes.

var x = Math.floor( mouse.x / canvas.width * 100 ); 
var y = Math.floor( mouse.y / canvas.height * 100 );

However when I try draw on the canvas with those x and z values I am not getting the correct positions.

The reason that I need the canvas / am trying to use percentage is that it is going to be an overlay on top of a video. And the user has to draw a rectangle around the video to get an offset because videos often display black sidebars for aspect ratios.

Here is a example of the canvas that does not put the rectangle in the right position:

http://jsfiddle.net/74CP8/

Edit: FYI: Firefox does not seem to run the jsfiddle properly due to the way jsfiddle works apparently. Try Chrome.

Schoening
  • 79
  • 1
  • 7
  • 1
    http://stackoverflow.com/a/20061533/856501 might help, it's a post i made about getting coordinates, which works when using css scaling. – GameAlchemist Jun 27 '14 at 14:16

1 Answers1

3

I'm not sure of what you want, but here it is 2 possible solutions :

The first allows you to move correctly your mouse in a scaled canvas

http://jsfiddle.net/74CP8/1/

The second allows you to draw a rectangle from the top left corner to the bottom right corner.

http://jsfiddle.net/74CP8/2/

Your problem was here :

ctx.rect(x,y,x+10, y+ 10)

You used x & y as percentages whereas you need its as pixels.

Don't hesitate if you have any other questions.

  • They work great! Thanks for the answer! Could you tell me what part you don't understand so I can edit my question? – Schoening Jun 27 '14 at 14:44
  • 1
    I'm happy that it suits you. I was not sure whether the user has to click, then moves the mouse and releases the click to draw the rectangle or just draw it as my solution 2 suggest. – Thomas Hourlier Jun 27 '14 at 14:51
  • Yeah. That is the end goal. But I figured I can find that out myself after :p – Schoening Jun 27 '14 at 15:31
  • Sorry but I have one more question. How do you deal with offsets? 0,0 to mouse position works fine. But anywhere else and the rect will shoot further than the mouse position. http://jsfiddle.net/74CP8/3/ – Schoening Jun 27 '14 at 16:54
  • Also resizing the browser after the script has loaded "confuses" the code – mallwright Sep 29 '22 at 14:47