如何在工具提示表单中使用纯javascript在画布上显示鼠标坐标?

时间:2010-12-21 01:09:49

标签: javascript html html5 canvas

所以关于html5画布。因此,当鼠标位于画布上时,我希望以鼠标靠近鼠标的方式看到类似x:11, y:33的内容,如alt text ...鼠标移动工具提示会随着显示坐标而移动。如何用javascript和html 5做这样的事情?

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:2)

我写了一个HTML5画布工具提示,可以做到这一点。它是用Processing.js库编写的,用于我正在编写的可视化Web应用程序,但它也可以从纯JavaScript中使用。您可以从GitHub Gist下载包含示例网页的代码。您可以阅读并查看实时示例,该示例恰好显示鼠标坐标here

相关问题