合成操作

globalCompositeOperation属性控制新绑制的内容如何与已有内容混合。

基本语法

ctx.globalCompositeOperation = type

所有合成模式

基础模式

模式说明
source-over默认,新图形覆盖在已有内容之上
source-in只显示新图形与已有内容重叠的部分
source-out只显示新图形不与已有内容重叠的部分
source-atop新图形只在与已有内容重叠处显示
destination-over已有内容覆盖在新图形之上
destination-in只显示已有内容与新图形重叠的部分
destination-out只显示已有内容不与新图形重叠的部分
destination-atop已有内容只在与新图形重叠处显示

混合模式

模式说明
lighter颜色值相加,变亮效果
multiply颜色值相乘,变暗效果
screen屏幕混合,变亮效果
overlay叠加混合,增强对比
darken取较暗的颜色
lighten取较亮的颜色
color-dodge颜色减淡
color-burn颜色加深
hard-light强光效果
soft-light柔光效果
difference差值效果
exclusion排除效果
hue使用新图形的色相
saturation使用新图形的饱和度
color使用新图形的色相和饱和度
luminosity使用新图形的亮度

特殊模式

模式说明
copy只显示新图形
xor异或运算,重叠部分透明

基础模式演示

基础合成模式

混合模式演示

混合模式效果

常用模式详解

source-over(默认)

新图形覆盖在已有内容之上,这是默认行为:

ctx.fillStyle = 'blue'
ctx.fillRect(50, 50, 100, 100)

ctx.globalCompositeOperation = 'source-over'
ctx.fillStyle = 'red'
ctx.fillRect(100, 100, 100, 100)  // 红色覆盖蓝色

destination-out(橡皮擦)

用新图形擦除已有内容:

ctx.fillStyle = '#3498db'
ctx.fillRect(0, 0, 200, 200)

ctx.globalCompositeOperation = 'destination-out'
ctx.beginPath()
ctx.arc(100, 100, 50, 0, Math.PI * 2)
ctx.fill()  // 擦除圆形区域

lighter(颜色叠加)

颜色值相加,产生变亮效果:

ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'
ctx.fillRect(50, 50, 100, 100)

ctx.globalCompositeOperation = 'lighter'
ctx.fillStyle = 'rgba(0, 0, 255, 0.5)'
ctx.fillRect(100, 50, 100, 100)  // 重叠处变亮

multiply(正片叠底)

颜色值相乘,产生变暗效果:

ctx.fillStyle = '#ff0000'
ctx.fillRect(50, 50, 100, 100)

ctx.globalCompositeOperation = 'multiply'
ctx.fillStyle = '#00ff00'
ctx.fillRect(100, 50, 100, 100)  // 重叠处变暗

橡皮擦效果演示

destination-out 橡皮擦效果

图像遮罩效果

source-in 遮罩效果

发光效果

lighter 发光效果

动态合成演示

动态合成效果

注意事项

模式顺序

globalCompositeOperation只影响之后的绑制操作。

重置模式

使用后记得重置为'source-over',避免影响其他绑制。

性能考虑

某些模式可能影响性能,在动画中谨慎使用。

透明度影响

合成模式与globalAlpha配合使用会产生不同效果。