Canvas-透明PNG图像阴影

使用Canvas为PNG图像绘制阴影。

绘制阴影

方法1:shadowBlur + shadowColor + shadowOffsetX + shadowOffsetY

MDN CanvasRenderingContext2D.shadowBlur

1
2
3
4
ctx.shadowBlur = 8;
ctx.shadowColor = 'rgba(0,0,0,0.3)';
ctx.shadowOffsetX = 100;
ctx.shadowOffsetY = 50;

关于shadowBlur单位问题

shadowBlur的值既不对应像素值也不受当前变换矩阵的影响:

This value doesn’t correspond to a number of pixels, and is not affected by the current transformation matrix

可以参考What are the units of CanvasRenderingContext2D.shadowBlur?这篇问答,有说明Canvas shadowBlur与CSS filter blur-radius的差别。

方法2:滤镜函数drop-shadow

MDN CanvasRenderingContext2D.filter

IE与Safari(包括iOS Safari)不支持。如果图像仅用于显示,可以用CSS3 filter(兼容Safari不兼容IE)代替。

1
ctx.filter = 'drop-shadow(50px 50px 10px rgba(0, 0, 0, 0.3))';

绘制内阴影

方法1:滤镜函数 drop-shadow + 合成操作globalCompositeOperation

MDN globalCompositeOperation

IE与Safari(包括iOS Safari)不支持filter滤镜。

方法来自Inset-shadow on HTML5 canvas image 提问的回答

方法2:合成操作 globalCompositeOperation + shadowBlur + shadowColor

方法来自Inset-shadow on HTML5 canvas image 提问的回答 Composition chain

4个步骤:

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