Canvas 07
组合 Compositing
对于合成的图形来说,绘制顺序有限制,我们可以使用globalCompositeOperation属性来改变这种情况,同时clip属性允许我们隐藏我们不想看到的部分图形。
globalCompositeOperation = type 该属性1设定了在绘制新图形时采用的遮盖策略,可以表示12中遮盖方式的字符串。
裁切路径
用于隐藏画布上不需要的部分
裁切效果与globalCompositeOperation属性中source-in和source-atop差不多的效果。裁切路径不会再画布上绘制任何图形且不受其他新图形的影响,我们可以限制绘制图形的区域。
clip() —— 将当前绘制的路径转换成裁切路径。
裁切路径也是属于canvas状态的一部分,可以被保留下来。 示例
function draw() {
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillRect(0, 0, 150, 150);
ctx.translate(75, 75);
// Create a circular clipping path
ctx.beginPath();
ctx.arc(0, 0, 60, 0, Math.PI * 2, true);
ctx.clip();
// draw background
var lingrad = ctx.createLinearGradient(0, -75, 0, 75);
lingrad.addColorStop(0, "#232256");
lingrad.addColorStop(1, "#143778");
ctx.fillStyle = lingrad;
ctx.fillRect(-75, -75, 150, 150);
// draw stars
for (var j = 1; j < 50; j++) {
ctx.save();
ctx.fillStyle = "#fff";
ctx.translate(
75 - Math.floor(Math.random() * 150),
75 - Math.floor(Math.random() * 150),
);
drawStar(ctx, Math.floor(Math.random() * 4) + 2);
ctx.restore();
}
}
function drawStar(ctx, r) {
ctx.save();
ctx.beginPath();
ctx.moveTo(r, 0);
for (var i = 0; i < 9; i++) {
ctx.rotate(Math.PI / 5);
if (i % 2 == 0) {
ctx.lineTo((r / 0.525731) * 0.200811, 0);
} else {
ctx.lineTo(r, 0);
}
}
ctx.closePath();
ctx.fill();
ctx.restore();
}
反转裁切路径
anticlockwise 当我们在绘制圆形时使用逆时针的方式,可以绘制一个中间空洞,只能在圆外绘制图形的反向裁切路径。
ctx.arc(0, 0, 60, 0, Math.PI * 2, true); // Hole anticlockwise
简言之,当我们在一个制定区域逆时针绘制裁切路径时,我们就能得到一个在限制区域在圆之外的反向蒙版。
写在最后
未完待续…
希望大家好好生活,健康快乐。