简体   繁体   中英

HTML 5 Canvas - Get real coordinate when zooming

I finally achieved to implement a zoomable and panning canvas using this code as a base https://stackoverflow.com/a/3151987/5221943 . Now I need to detect the real coordinate where the user clicked inside the canvas. I don't know how to convert the mouse page coordinate to the real world coordinate taking into account the user has already zoomed or panned the canvas. Any suggestion here?

Here the code for gating the coordinates of the canvas

 Call the DumpInfo function in the html canvas tag like <canvas id="canvas" width="600" height="200" onmousedown="DumpInfo(event)"></canvas> Bellow two functions defined <script type = "text/javascript" > function DumpInfo(event) { var info = document.getElementById("canvas"); //info.innerHTML += event.type + ", "; var pos = getMousePos(info, event); alert(pos.x); alert(pos.y); } function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM