globalAlpha 透明度设置

globalAlpha属性用于设置Canvas的全局透明度,影响所有后续绑制操作。

基本语法

ctx.globalAlpha = value
参数类型说明
valuenumber透明度值,范围0.0-1.0

基本用法

const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

// 设置全局透明度
ctx.globalAlpha = 0.5

// 绘制半透明图形
ctx.fillStyle = '#3498db'
ctx.fillRect(50, 50, 100, 100)

ctx.fillStyle = '#e74c3c'
ctx.fillRect(100, 100, 100, 100)

// 恢复完全不透明
ctx.globalAlpha = 1.0

透明度演示

不同透明度效果

globalAlpha与rgba对比

// 使用globalAlpha
ctx.globalAlpha = 0.5
ctx.fillStyle = '#3498db'
ctx.fillRect(50, 50, 100, 100)

// 使用rgba
ctx.globalAlpha = 1.0
ctx.fillStyle = 'rgba(52, 152, 219, 0.5)'
ctx.fillRect(200, 50, 100, 100)

对比演示

globalAlpha与rgba对比

叠加效果

// 多个透明图形叠加
ctx.globalAlpha = 0.3
ctx.fillStyle = '#e74c3c'
ctx.fillRect(50, 50, 100, 100)

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

ctx.fillStyle = '#2ecc71'
ctx.fillRect(75, 100, 100, 100)

叠加效果演示

透明叠加效果

注意事项

透明度叠加

// globalAlpha会叠加
ctx.globalAlpha = 0.5
ctx.globalAlpha = 0.5
// 实际透明度不是0.25,而是0.5(最后设置的值)

影响所有操作

ctx.globalAlpha = 0.5

// 影响填充
ctx.fillRect(0, 0, 50, 50)

// 影响描边
ctx.strokeRect(60, 0, 50, 50)

// 影响文本
ctx.fillText('半透明文字', 0, 100)

// 影响图像
ctx.drawImage(image, 0, 0)

及时恢复

// 绘制半透明图形
ctx.globalAlpha = 0.5
ctx.fillRect(0, 0, 100, 100)

// 恢复默认值
ctx.globalAlpha = 1.0

// 绘制不透明图形
ctx.fillRect(110, 0, 100, 100)

使用save/restore

// 保存状态
ctx.save()

// 设置透明度
ctx.globalAlpha = 0.5
ctx.fillRect(0, 0, 100, 100)

// 恢复状态(包括透明度)
ctx.restore()

// 绘制不透明图形
ctx.fillRect(110, 0, 100, 100)

状态管理演示

使用save/restore管理透明度