McKracken
McKracken

Reputation: 389

HTML5 Getting inner coordinates of canvas inside scrollable div

I have a canvas in which I draw an image (it represents a map) of 4000x4000 pixels. The canvas is embedded in a scrollable div, whose size is less the the canvas size. I need to get the coordinates over which the mouse pointer passes with respect to the 4000x4000 image drawn in the canvas, this meaning it need to take into account also the possible scrolling.

<div class="" style="overflow: scroll; width:450px; height:200px;">
    <canvas id="map" onmousemove="getMousePos(event)">
    </canvas>
</div>

Upvotes: 1

Views: 461

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

You can get accurate x and y mouse coordinates, relative to the canvas using offsetX and offsetY property of MouseEvent.

function getMousePos(event) {
   var x = event.offsetX;
   var y = event.offsetY;
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

function getMousePos(event) {
   var x = event.offsetX;
   var y = event.offsetY;
   console.clear();
   console.log(x, y);
}
<div class="cont" style="overflow: scroll; width:450px; height:400px;">
    <canvas id="map" width="4000" height="4000" onmousemove="getMousePos(event)" style="background-color: red;"/>
</div>

Upvotes: 1

Related Questions