region 使用0代表空 1代表有
复制到codepen执行
// 创建三个 Canvas 元素
const intersectionCanvas = document.createElement('canvas');
const unionCanvas = document.createElement('canvas');
const differenceCanvas = document.createElement('canvas');intersectionCanvas.width = unionCanvas.width = differenceCanvas.width = 100;
intersectionCanvas.height = unionCanvas.height = differenceCanvas.height = 100;document.body.appendChild(intersectionCanvas);
document.body.appendChild(unionCanvas);
document.body.appendChild(differenceCanvas);const intersectionCtx = intersectionCanvas.getContext('2d');
const unionCtx = unionCanvas.getContext('2d');
const differenceCtx = differenceCanvas.getContext('2d');// 创建旋转矩形
function createRotatedRect(centerX, centerY, width, height, angle) {const shape = new Array(10000).fill(0); // 100x100 大小的画布for (let i = 0; i < 100; i++) {for (let j = 0; j < 100; j++) {const x = i - centerX;const y = j - centerY;const rotatedX = Math.cos(angle) * x - Math.sin(angle) * y;const rotatedY = Math.sin(angle) * x + Math.cos(angle) * y;if (rotatedX >= -width / 2 && rotatedX <= width / 2 && rotatedY >= -height / 2 && rotatedY <= height / 2) {shape[i * 100 + j] = 1; // 在旋转矩形内部标记为1}}}return shape;
}// 创建形状
const shape1 = createRotatedRect(50, 50, 70, 30, Math.PI / 6); // 创建一个旋转矩形
const shape2 = createShape2(); // 创建一个圆形// 计算交集
const intersection = calculateIntersection(shape1, shape2);
drawBinaryImage(intersectionCtx, intersection, 'green');// 计算并集
const union = calculateUnion(shape1, shape2);
drawBinaryImage(unionCtx, union, 'blue');// 计算差集
const difference = calculateDifference(shape1, shape2);
drawBinaryImage(differenceCtx, difference, 'red');// 创建第二个形状(圆形)
function createShape2() {const shape = new Array(10000).fill(0); // 100x100 大小的画布const centerX = 50, centerY = 50, radius = 25;for (let i = 0; i < 100; i++) {for (let j = 0; j < 100; j++) {const distance = Math.sqrt((i - centerX) ** 2 + (j - centerY) ** 2);if (distance <= radius) {shape[i * 100 + j] = 1; // 在中心创建一个圆形}}}return shape;
}// 计算交集
function calculateIntersection(shape1, shape2) {return shape1.map((pixel, index) => pixel && shape2[index] ? 1 : 0);
}// 计算并集
function calculateUnion(shape1, shape2) {return shape1.map((pixel, index) => pixel || shape2[index] ? 1 : 0);
}// 计算差集
function calculateDifference(shape1, shape2) {return shape1.map((pixel, index) => pixel && !shape2[index] ? 1 : 0);
}// 将二值图绘制到 Canvas 上
function drawBinaryImage(ctx, binaryImage, color) {ctx.fillStyle = color;binaryImage.forEach((pixel, index) => {if (pixel) {const x = index % 100;const y = Math.floor(index / 100);ctx.fillRect(x, y, 1, 1);}});
}