简体   繁体   English

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

[英]How to show some text on mouseover when using canvas and hide on mouseout

I have a canvas element which is a canvas element made up of a bunch of images. 我有一个canvas元素,它是一个由一堆图像组成的canvas元素。 I want to add a label to each image on the canvas but only want it to show up when the user hovers over the correct image. 我想为画布上的每个图像添加一个标签,但只希望它在用户将鼠标悬停在正确的图像上时显示。

I have managed to get some text to show up but I cant work out how only to show it on mouseover and to not show on mouseleave. 我设法得到一些文本,但我不知道如何只在鼠标悬停时显示它并且不显示在mouseleave上。 Currently I am checking to see if the mouse position matches the mouse position of the points array. 目前我正在检查鼠标位置是否与点数组的鼠标位置匹配。 If it does it adds the text. 如果是,则添加文本。

    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
    };
  };

Essentially I want the 'Hello' to show up but only when you are hovering over the correct position. 基本上我希望“你好”出现,但只有当你盘旋在正确位置时才会出现。

A simple way to do this is by getting the mouse x and y from the event, and comparing it to the x, y, width, and height of the image. 一种简单的方法是从事件中获取鼠标x和y,并将其与图像的x,y,宽度和高度进行比较。

Look through this snippet: 仔细阅读以下代码段:

 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; } 
 <canvas id="canvas" width="500" height="250"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM