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 | 异或运算,重叠部分透明 |
新图形覆盖在已有内容之上,这是默认行为:
ctx.fillStyle = 'blue'
ctx.fillRect(50, 50, 100, 100)
ctx.globalCompositeOperation = 'source-over'
ctx.fillStyle = 'red'
ctx.fillRect(100, 100, 100, 100) // 红色覆盖蓝色
用新图形擦除已有内容:
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() // 擦除圆形区域
颜色值相加,产生变亮效果:
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) // 重叠处变亮
颜色值相乘,产生变暗效果:
ctx.fillStyle = '#ff0000'
ctx.fillRect(50, 50, 100, 100)
ctx.globalCompositeOperation = 'multiply'
ctx.fillStyle = '#00ff00'
ctx.fillRect(100, 50, 100, 100) // 重叠处变暗
模式顺序
globalCompositeOperation只影响之后的绑制操作。
重置模式
使用后记得重置为'source-over',避免影响其他绑制。
性能考虑
某些模式可能影响性能,在动画中谨慎使用。
透明度影响
合成模式与globalAlpha配合使用会产生不同效果。