Rella
Rella

Reputation: 66965

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

So its about html5 canvas. So I want to see something like x:11, y:33 in form of tooltip near to mouse when mouse is on canvas like alt text... mouse moves tooltip moves with it showing coordinates. How to do such thing with javascript and html 5?

Upvotes: 4

Views: 8966

Answers (2)

user372551
user372551

Reputation:

$(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>

A simple Demo

Upvotes: 11

James Durbin
James Durbin

Reputation: 31

I wrote an HTML5 canvas tooltip that will do this. It's written with the Processing.js library for a visualization web-app I'm writing, but it can be used from pure javascript also. You can download the code with example web page from GitHub Gist. You can read about and see a live example, which happens to show the mouse coordinates, here.

Upvotes: 3

Related Questions