简体   繁体   中英

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. 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. 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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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