Michael Schwartz
Michael Schwartz

Reputation: 8425

Subtract Display Pixels from Mouse Position

Full code can be viewed on JSBin - http://jsbin.com/inibAya/1/edit

So I'm working on a wysiwyg website designer and I added a crosshair to show the corrinates the mouse position is within the canvas. (NOTE: a div acts as the canvas not a html5 canvas element)

The div#canvas is positioned at...

#canvas {
    position: absolute;
    top:0; left:44px; right:291px; bottom:16px;
    overflow: auto;
}

Whatever calculation I tried to remove the 44px from the canvas's display I got NaN or undefined. When the user moves their mouse I want it to start at 0 from the top left and move onwards. Does anyone know of anyway to get this to work?

Here's my JQuery/JavaScript:

// Crosshair
var cH = $('#crosshair-h'), cV = $('#crosshair-v');

$('#canvas').mousemove(function(e) {
    cH.css('top', e.pageY);
    cV.css('left', e.pageX);
    $('#mousepos').text( "X: " + e.pageX + "px, Y: " + e.pageY + "px");
});

Upvotes: 0

Views: 231

Answers (1)

Jackson Ray Hamilton
Jackson Ray Hamilton

Reputation: 9466

From e.pageX's documentation:

Description: The mouse position relative to the left edge of the document.

You will need to account for your canvas's offset (of 44px) to solve your problem.

var canvasPosition = $(canvas).position();

$(canvas).on('mousemove', function(e) {
  var x = e.pageX - canvasPosition.left;
  var y = e.pageY - canvasPosition.top;
  cH.css('top', e.pageY);
  cV.css('left', e.pageX);
  $('#mousepos').text( "X: " + x + "px, Y: " + y + "px");
});

JSBin.

Upvotes: 1

Related Questions