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

Rel*_*lla 4 html javascript html5 canvas

所以它关于html5画布.因此x:11, y:33,当鼠标在画布上时,我希望看到像鼠标附近工具提示的形式替代文字...鼠标移动工具提示移动,显示坐标.如何用javascript和html 5做这样的事情?

小智 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);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>
Run Code Online (Sandbox Code Playgroud)

一个简单的演示