Update HTML5 canvas rectangle on hover?

后端 未结 8 765
暗喜
暗喜 2020-12-03 01:57

I\'ve got some code which draws a rectangle on a canvas, but I want that rectangle to change color when I hover the mouse over it.

The problem is after I\'ve drawn t

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 02:21

    You can't do this out-of-the-box with canvas. Canvas is just a bitmap, so the hover logic has to be implemented manually.

    Here is how:

    • Store all the rectangles you want as simple object
    • For each mouse move on the canvas element:
      • Get mouse position
      • Iterate through the list of objects
      • use isPointInPath() to detect a "hover"
      • Redraw both states

    Example

    var canvas = document.querySelector("canvas"),
        ctx = canvas.getContext("2d"),
        rects = [
            {x: 10, y: 10, w: 200, h: 50},
            {x: 50, y: 70, w: 150, h: 30}    // etc.
        ], i = 0, r;
    
    // render initial rects.
    while(r = rects[i++]) ctx.rect(r.x, r.y, r.w, r.h);
    ctx.fillStyle = "blue"; ctx.fill();
    
    canvas.onmousemove = function(e) {
    
      // important: correct mouse position:
      var rect = this.getBoundingClientRect(),
          x = e.clientX - rect.left,
          y = e.clientY - rect.top,
          i = 0, r;
      
      ctx.clearRect(0, 0, canvas.width, canvas.height); // for demo
       
      while(r = rects[i++]) {
        // add a single rect to path:
        ctx.beginPath();
        ctx.rect(r.x, r.y, r.w, r.h);    
        
        // check if we hover it, fill red, if not fill it blue
        ctx.fillStyle = ctx.isPointInPath(x, y) ? "red" : "blue";
        ctx.fill();
      }
    
    };

提交回复
热议问题