透明度
除了可以绘制实色图形,还可以用canvas
来绘制半透明的图形。通过设置globalAlpha
属性或者使用一个半透明颜色作为轮廓或填充的样式。
globalAlpha = transparencyValue
这个属性影响到canvas
里所有图形的透明度,有效的值范围是0.0(完全透明)到1.0(完全不透明),默认值是1.0。
globalAlpha
属性在需要绘制大量拥有相同透明度的图形时候相当高效。不过,我认为下面的方法可操作性更强一点。
因为strokeStyle
和fillStyle
属性接受符合CSS3
规范的颜色值,所以我们可以用rgba
的写法来设置具有透明度的颜色。
// 指定透明颜色,用于描边和填充样式
ctx.strokeStyle = "rgba(255, 0, 0, 0.5)";
ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
rgba()
方法与 rgb()
方法类似,就多了一个用于设置色彩透明度的参数。它的有效范围是从 0.0(完全透明)到 1.0(完全不透明)。
globalAlpha
示例
在这个例子里,将用四色格作为背景,设置globalAlpha
为0.2
后,在上面画一系列半径递增的半透明圆。最终结果是一个径向渐变效果。圆叠加得越多,原先所画的圆的透明度会越低。通过增加循环次数,画更多的圆,从中心到边缘部分,背景图会呈现逐渐消失的效果。
实现效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alpha Demo</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
function draw() {
var ctx = document.getElementById("canvas").getContext("2d");
// 画背景
ctx.fillStyle = "#fd0";
ctx.fillRect(0, 0, 75, 75);
ctx.fillStyle = "#6c0";
ctx.fillRect(75, 0, 75, 75)
ctx.fillStyle = "#09f"
ctx.fillRect(0, 75, 75, 75)
ctx.fillStyle = "#f30"
ctx.fillRect(75, 75, 75, 75)
ctx.fillStyle = "#fff"
// 设置透明度
ctx.globalAlpha = 0.2
// 画半透明圆
for(let i = 0; i < 7; i++) {
ctx.beginPath()
ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI*2, true)
ctx.fill()
}
}
draw()
</script>
</html>
rgba()
示例
第二个例子和上面的那个类似,不过不是画圆,而是画矩形。这里还可以看出,rgba()
可以分别设置轮廓和填充样式,因而具有更好的可操作性和使用灵活性。
实现效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rgba Demo</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
function draw() {
var ctx = document.getElementById("canvas").getContext("2d");
// 画背景
ctx.fillStyle = "rgb(255, 211, 0)";
ctx.fillRect(0, 0, 150, 37.5);
ctx.fillStyle = "rgb(102, 204, 0)";
ctx.fillRect(0, 37.5, 150, 37.5);
ctx.fillStyle = "rgb(0, 153, 255)";
ctx.fillRect(0, 75, 150, 37.5);
ctx.fillStyle = "rgb(255, 51, 0)";
ctx.fillRect(0, 112.5, 150, 37.5);
// 画半透明矩形
for (let i = 0; i < 10; i++) {
ctx.fillStyle = `rgba(255, 255, 255, ${(i + 1) / 10})`
for (let j = 0; j < 4; j++) {
ctx.fillRect(5 + i * 14, 5 + j * 37.5, 14, 27.5)
}
}
}
draw()
</script>
</html>