最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to show mouse coordinates over canvas using pure javascript in tooltip form? - Stack Overflow

programmeradmin4浏览0评论

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 ... mouse moves tooltip moves with it showing coordinates. How to do such thing with javascript and html 5?

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 ... mouse moves tooltip moves with it showing coordinates. How to do such thing with javascript and html 5?

Share Improve this question edited Dec 21, 2010 at 1:17 Rella asked Dec 21, 2010 at 1:09 RellaRella 67k112 gold badges373 silver badges642 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 11

$(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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>

A simple Demo

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.

发布评论

评论列表(0)

  1. 暂无评论