Inset-shadow on HTML5 canvas image

后端 未结 5 1978
遥遥无期
遥遥无期 2021-01-03 15:19

I\'ve seen this question before but the answers given are for canvas images that have been drawn on via path however, i\'m drawing an image.

Is it possible to creat

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 15:55

    Composition chain

    Use a series of composite + draw operation to obtain inset shadow.

    Note: the solution require exclusive access to the canvas element when created so either do this on an off-screen canvas and draw back to main, or if possible, plan secondary graphics to be drawn after this has been generated.

    The needed steps:

    • Draw in original image
    • Invert alpha channel filling the canvas with a solid using xor composition
    • Define shadow and draw itself back in
    • Deactivate shadow and draw in original image (destination-atop)

    Result

    var ctx = c.getContext("2d"), img = new Image;
    img.onload = function() {
    
      // draw in image to main canvas
      ctx.drawImage(this, 0, 0);
    
      // invert alpha channel
      ctx.globalCompositeOperation = "xor";
      ctx.fillRect(0, 0, c.width, c.height);
    
      // draw itself again using drop-shadow filter
      ctx.shadowBlur = 7*2;  // use double of what is in CSS filter (Chrome x4)
      ctx.shadowOffsetX = ctx.shadowOffsetY = 5;
      ctx.shadowColor = "#000";
      ctx.drawImage(c, 0, 0);
    
      // draw original image with background mixed on top
      ctx.globalCompositeOperation = "destination-atop";
      ctx.shadowColor = "transparent";                  // remove shadow !
      ctx.drawImage(this, 0, 0);
    }
    img.src = "http://i.imgur.com/Qrfga2b.png";

提交回复
热议问题