全局透明度

Canvas globalAlpha属性详解,掌握全局透明度设置、与RGBA的区别和实际应用技巧。globalAlpha属性设置全局透明度,影响之后所有绑制操作的透明度。

基本语法

ctx.globalAlpha = value
参数类型说明
valuenumber透明度值,范围0.0(完全透明)到1.0(完全不透明)

工作原理

globalAlpha设置一个全局透明度值,之后所有的绑制操作都会受到这个值的影响:

ctx.globalAlpha = 0.5  // 设置50%透明度
ctx.fillRect(0, 0, 100, 100)  // 以50%透明度绘制

基本透明度演示

不同透明度效果

globalAlpha vs RGBA透明度

globalAlpha

设置全局透明度,影响所有后续绑制:

ctx.globalAlpha = 0.5
ctx.fillStyle = 'red'
ctx.fillRect(0, 0, 100, 100)  // 50%透明
ctx.fillStyle = 'blue'
ctx.fillRect(50, 50, 100, 100)  // 50%透明

RGBA透明度

在颜色中直接设置透明度:

ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'
ctx.fillRect(0, 0, 100, 100)  // 50%透明
ctx.fillStyle = 'rgba(0, 0, 255, 0.5)'
ctx.fillRect(50, 50, 100, 100)  // 50%透明

累积效应

globalAlpha会与颜色透明度累积:

ctx.globalAlpha = 0.5
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'
ctx.fillRect(0, 0, 100, 100)  // 实际透明度 = 0.5 * 0.5 = 0.25

对比演示

globalAlpha vs RGBA

透明度叠加

当多个半透明图形重叠时,会产生叠加效果:

透明度叠加效果

实际应用

1. 淡入淡出效果

let alpha = 0

function fadeIn() {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  ctx.globalAlpha = alpha
  ctx.drawImage(image, 0, 0)
  
  alpha += 0.02
  if (alpha < 1) {
    requestAnimationFrame(fadeIn)
  }
}

2. 水印效果

ctx.drawImage(image, 0, 0)

ctx.globalAlpha = 0.3
ctx.fillStyle = '#fff'
ctx.font = '20px Arial'
ctx.fillText('WATERMARK', 50, 50)
ctx.globalAlpha = 1.0

3. 半透明遮罩

ctx.drawImage(image, 0, 0)

ctx.globalAlpha = 0.5
ctx.fillStyle = '#000'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.globalAlpha = 1.0

ctx.fillStyle = '#fff'
ctx.fillText('Loading...', canvas.width / 2, canvas.height / 2)

淡入淡出动画

淡入淡出效果

水印效果演示

水印效果

重置透明度

使用后记得重置为1.0:

ctx.globalAlpha = 0.5
// 绑制操作
ctx.globalAlpha = 1.0  // 重置

注意事项

累积效应

globalAlpha会与颜色本身的透明度累积。

影响范围

globalAlpha影响之后所有的绑制操作,包括图像、文本等。

性能考虑

频繁修改globalAlpha可能影响性能。

默认值

默认值为1.0(完全不透明)。