在画布上鼠标悬停在形状/位置(坐标)上时显示工具提示

5

我想在画布的某些位置鼠标悬停时显示相应的工具提示。例如,当鼠标在画布上的坐标为(100,100)时,显示工具提示1。当鼠标位置在(200,200)时,显示工具提示2等。

我已经添加了事件监听器来检测鼠标移动并获取鼠标位置。这是我的代码:

window.addEventListener('mousemove',hover,false);
function getMousePos (canvas, event) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}
function hover (event){
    pos = getMousePos(canvas,event);
    if (condition to detect mouse hover)
    //display tooltip_function (this is the function that I don't know how to implement)
}

这个可能会有所帮助,如果你搜索一下还有其他几个。 - user1693593
1个回答

9
您可以通过以下方式测试鼠标是否悬停在您的圆形热点之一上:
var hotspots=[
    {x:100,y:100,radius:20,tip:'You are over 100,100'},
    {x:100,y:200,radius:20,tip:'You are over 100,200'},
];

var dx=mouseX-hotspot[0].x;
var dy=mouseY-hotspot[0].y;

if (dx * dx + dy * dy < hotspot[0].radius * hotspot[0].radius) {
  // it's over hotspot[0]
}

以下是示例代码和演示:

注意:您不必像演示中那样显示圆形热点-这只是为了演示而已

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
function reOffset() {
  var BB = canvas.getBoundingClientRect();
  offsetX = BB.left;
  offsetY = BB.top;
}
var offsetX, offsetY;
reOffset();
window.onscroll = function (e) {
  reOffset();
};
window.onresize = function (e) {
  reOffset();
};

var hotspots = [
  { x: 100, y: 100, radius: 20, tip: "You are over 100,100" },
  { x: 100, y: 200, radius: 20, tip: "You are over 100,200" },
];

draw();

$("#canvas").mousemove(function (e) {
  handleMouseMove(e);
});

function draw() {
  for (var i = 0; i < hotspots.length; i++) {
    var h = hotspots[i];
    ctx.beginPath();
    ctx.arc(h.x, h.y, h.radius, 0, Math.PI * 2);
    ctx.closePath();
    ctx.stroke();
  }
}

function handleMouseMove(e) {
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX = parseInt(e.clientX - offsetX);
  mouseY = parseInt(e.clientY - offsetY);

  ctx.clearRect(0, 0, cw, ch);
  draw();
  for (var i = 0; i < hotspots.length; i++) {
    var h = hotspots[i];
    var dx = mouseX - h.x;
    var dy = mouseY - h.y;
    if (dx * dx + dy * dy < h.radius * h.radius) {
      ctx.fillText(h.tip, h.x, h.y);
    }
  }
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Hover over a hotspot circle</h4>
<canvas id="canvas" width=300 height=300></canvas>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接