globalCompositeOperation属性可以决定canvas中两个图形或路径叠加之后产生的效果
属性值共有26种
下面画两个球实际感受一下:
先画一个红色球
再画一个橙色球
不同的结果如下:
作用效果还是比较明显的,
最后再上一小段代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
width: 1230px;
margin: 0 auto;
padding-top: 5px;
}
canvas {
border: 1px solid pink;
margin-left: 5px;
}
</style>
</head>
<body onload="draw()">
<script>
let w = '300';
let h = '300';
let compositing = ['source-over', 'source-in', 'source-out', 'source-atop', 'destination-over', 'destination-in', 'destination-out', 'destination-atop', 'lighter', 'copy', 'xor', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'];
let len = compositing.length;
let first = document.body.firstChild;
function draw() {
/** @type {HTMLCanvasElement} */
for (let i = 0; i < len; i++) {
let canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
document.body.insertBefore(canvas, first);
}
let canvas = document.querySelectorAll('canvas');
for (let i = 0; i < canvas.length; i++) {
let ctx = canvas[i].getContext('2d');
ctx.save();
ctx.translate(w / 2, h / 2);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(-40, 20, 80, 0, Math.PI * 2, 1);
ctx.closePath();
ctx.fill();
ctx.globalCompositeOperation = compositing[i];
ctx.fillStyle = 'orange';
ctx.beginPath();
ctx.arc(40, 20, 80, 0, Math.PI * 2, 1);
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.fillStyle = 'black';
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.font = '30px Arial';
ctx.fillText((i + 1) + ':' + compositing[i], w / 2, 40);
}
}
</script>
</body>
</html>