How to show mouse coordinates over a canvas using pure javascript in the form of a tooltip?

So this is about html5 canvas. So I want to see something like x:11, y:33 as a tooltip next to the mouse, when the mouse is on canvas, like alt text ... the mouse moves the tooltip by moving it, showing the coordinates. How to do this with javascript and html 5?

+4
source share
2 answers

 $(function() { var canvas = $('#canvas').get(0); var ctx = canvas.getContext('2d'); var w = h = canvas.width = canvas.height = 300; ctx.fillStyle = '#0099f9'; ctx.fillRect(0, 0, w, h); canvas.addEventListener('mousemove', function(e) { var x = e.pageX - canvas.offsetLeft; var y = e.pageY - canvas.offsetTop; var str = 'X : ' + x + ', ' + 'Y : ' + y; ctx.fillStyle = '#0099f9'; ctx.fillRect(0, 0, w, h); ctx.fillStyle = '#ddd'; ctx.fillRect(x + 10, y + 10, 80, 25); ctx.fillStyle = '#000'; ctx.font = 'bold 20px verdana'; ctx.fillText(str, x + 20, y + 30, 60); }, 0); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <canvas id="canvas"></canvas> 

Simple demonstration

+9
source

I wrote a hint for an HTML5 canvas that will do this. This is written using the Processing.js library for the visualization web application that I am writing, but it can also be used from pure javascript. You can download the code from the sample webpage from the GitHub Gist . You can read and see a live example that shows the coordinates of the mouse, here .

+2
source

Source: https://habr.com/ru/post/1332850/


All Articles