如何在使用画布时在鼠标悬停时显示一些文本并在鼠标悬停时隐藏

时间:2019-06-04 19:21:54

标签: javascript canvas

我有一个canvas元素,它是由一堆图像组成的canvas元素。我想在画布上的每个图像上添加标签,但只希望当用户将鼠标悬停在正确的图像上时才显示标签。

我设法显示了一些文本,但是我想不出如何只在鼠标悬停时显示它而不在mouseleave上显示。目前,我正在检查鼠标位置是否与points数组的鼠标位置匹配。如果这样做,则会添加文本。

    canvas.addEventListener('mousemove', handleMouseMove.bind(this));


var handleMouseMove = function (e) {
    var mousePos = getSquare(canvas, e);
    var pos = points.filter((item => mousePos.x === item.x && mousePos.y === item.y));
    var hit = false;
    if (pos && pos.length) {
      context.fillStyle = "#ffffff";
      console.log(pos);
      context.fillText('Hello', pos[0].x, pos[0].y);
    } else {
      context.fillStyle = "#ffffff00";
      return;
    }
  };

  var getSquare = function (canvas, evt) {
    context.globalCompositeOperation = 'source-atop';
    var rect = canvas.getBoundingClientRect();
    return {
      x: 1 + (evt.clientX - rect.left) - (evt.clientX - rect.left) % 20,
      y: 1 + (evt.clientY - rect.top) - (evt.clientY - rect.top) % 20
    };
  };

基本上,我希望显示“ Hello”,但仅当您将鼠标悬停在正确的位置上时。

1 个答案:

答案 0 :(得分:0)

一种简单的方法是从事件中获取鼠标x和y,并将其与图像的x,y,宽度和高度进行比较。

浏览以下代码段:

def sum67(arr):
    for n in range (0, len(arr)):
        if arr[n] == 6:
            Sum1 = sum(arr[0:n])
            print ("Before 6 Sum Numbers:", Sum1)
    for k in range (0, len(arr)):
        if arr[k] ==7:
            Sum2 = sum(arr[(k)+1:])
            print ("After 7 Sum Numbers:", Sum2)
    if 6 and 7 in arr:
        print("Last Result")
        return (Sum1+Sum2)
    else:
        print("Last Result")
        return sum(arr)
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");

cxt.font = "50px georgia";

function clear() { // Clears screen to prevent smearing
  cxt.fillStyle = "white";
  cxt.fillRect(0, 0, 500, 250);
}

function drawrect() { // Draws rectangle
  cxt.fillStyle = "gray";
  cxt.fillRect(50, 50, 200, 100);
}

clear();
drawrect();

canvas.addEventListener("mousemove", (event) => { // When mouse is moved on canvas
  var x = event.offsetX;
  var y = event.offsetY;
  clear();
  drawrect();
  if (x > 50 && x < 250 &&
      y > 50 && y < 150) { // If mouse x and y are inside rectangle
      cxt.fillStyle = "red";
      cxt.fillText("Hello", x, y); // Draw text
  }
});
canvas {
  border: 1vw solid black;
}