代码
![并集](https://img-blog.csdnimg.cn/direct/3d39602e6add4b61a94ad2bc813b6513.png)
![差集](https://img-blog.csdnimg.cn/direct/0ebda5e15fd74139ab73e12d90abd527.png)
![交集](https://img-blog.csdnimg.cn/direct/397bd5e5fed44795a4c2b62c1ab7f9c2.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Demo</title>
<style>
canvas {
border: 1px solid black;
margin-bottom: 10px;
}
button {
margin-right: 10px;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<button onclick="changeOperation('Union')">Union</button>
<button onclick="changeOperation('Diff')">Diff</button>
<button onclick="changeOperation('Inter')">Inter</button>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let currentOperation = 'Union'; // 初始为并集
function drawShape(shape, color) {
ctx.fillStyle = color;
shape.draw(ctx);
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function changeOperation(operation) {
currentOperation = operation;
draw();
}
function draw() {
clearCanvas();
// 绘制第一个形状(矩形)
const rect = {
draw: function(ctx) {
ctx.fillRect(50, 50, 100, 100);
}
};
drawShape(rect, 'blue');
// 设置不同的操作
ctx.globalCompositeOperation = getCompositeOperation(currentOperation);
// 绘制第二个形状(圆形)
const circle = {
draw: function(ctx) {
ctx.beginPath();
ctx.arc(150, 150, 50, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
};
drawShape(circle, 'red');
}
function getCompositeOperation(operation) {
switch (operation) {
case 'Union':
return 'source-over';
case 'Diff':
return 'source-out';
case 'Inter':
return 'source-in';
default:
console.error('Invalid operation.');
return 'source-over';
}
}
// 初始化绘制
draw();
</script>
</body>
</html>