Click through PNG image - only if clicked coordinate is transparent

前端 未结 2 554
遇见更好的自我
遇见更好的自我 2021-01-04 06:38

I have an image like this:

I want it so that when I click the transparent parts, the click should go through to the underlying element, but when I click a n

2条回答
  •  孤城傲影
    2021-01-04 07:15

    1. Use a temporary canvas element.
    2. Get the overlay image mousedown coordinates.
    3. Populate your canvas with that image data.
    4. Read from canvas the 1px image data (from the same coordinates).
      If the retrieved Alpha channel data is 0 means it's transparent.
    5. If pixel is transparent set pointerEvents to "none" and retrieve the underneath element using Document.elementFromPoint
    6. Trigger "click" event on the underneath element
    7. Reset pointerEvents back to "auto" for all overlays

    var ctx = document.createElement("canvas").getContext("2d");
    
    $('#logo').on("mousedown", function(event) {
      
      // Get click coordinates
      var x = event.pageX - this.offsetLeft,
          y = event.pageY - this.offsetTop,
          w = ctx.canvas.width = this.width,
          h = ctx.canvas.height = this.height,
          alpha;
    
      // Draw image to canvas
      // and read Alpha channel value
      ctx.drawImage(this, 0, 0, w, h);
      alpha = ctx.getImageData(x, y, 1, 1).data[3]; // [0]R [1]G [2]B [3]A
    
      // If pixel is transparent,
      // retrieve the element underneath and trigger it's click event
      if( alpha===0 ) {
        this.style.pointerEvents = "none";
        $(document.elementFromPoint(event.clientX, event.clientY)).trigger("click");
        this.style.pointerEvents = "auto";
      } else {
        console.log("LOGO clicked!");
      }
    });
    
    
    $("#green").on("click", function(){
      console.log("Green image clicked!");
    });
    img{border:1px solid #000;}
    img + img{position:absolute;top:0; left:0;}
    
    
    

提交回复
热议问题