Canvas globalAlpha属性详解,掌握全局透明度设置、与RGBA的区别和实际应用技巧。globalAlpha属性设置全局透明度,影响之后所有绑制操作的透明度。
ctx.globalAlpha = value
| 参数 | 类型 | 说明 |
|---|---|---|
| value | number | 透明度值,范围0.0(完全透明)到1.0(完全不透明) |
globalAlpha设置一个全局透明度值,之后所有的绑制操作都会受到这个值的影响:
ctx.globalAlpha = 0.5 // 设置50%透明度
ctx.fillRect(0, 0, 100, 100) // 以50%透明度绘制
设置全局透明度,影响所有后续绑制:
ctx.globalAlpha = 0.5
ctx.fillStyle = 'red'
ctx.fillRect(0, 0, 100, 100) // 50%透明
ctx.fillStyle = 'blue'
ctx.fillRect(50, 50, 100, 100) // 50%透明
在颜色中直接设置透明度:
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
当多个半透明图形重叠时,会产生叠加效果:
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)
}
}
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
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(完全不透明)。