1. 场景描述
在我的业务需求中,有一个功能是实现套索,并且用户圈套的部分如果为偶数次则默认用户不需要该偶数次的内容。如下图:
画图步骤:第一步先画外圈(较大),第二步画内圈(较小)即类似于同心圆。那么第二个圆为偶数次填充则默认用户不需要。
2. 相信大家都看过很多预设的图像使用奇偶规则填充的案例了:如下
但是这个并不是我的业务场景所需要用到的,我的需求是通过笔触的绘画(即未知渲染点),将二次绘制的部分使用奇偶原则。
3. API使用和参考:
参考链接:fill(path,fillRule)

对于path2D的使用,在上面的链接中也有提到过。
4. 代码展示
<!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>
html,
body {
margin: 0;
}
</style>
</head>
<body>
<canvas id="haha"></canvas>
</body>
<script>
const canvas = document.getElementById('haha');
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight - 5;
const ctx = canvas.getContext('2d');
var points = [];
var paths = [];
var drawNow = false;
const draw = () => {
paths = [];
for (var i = 0; i < points.length; i++) {
if (i == 0) {
paths[i] = new Path2D();
} else {
paths[i] = new Path2D(paths[i - 1]);
}
paths[i].moveTo(points[i][0].x, points[i][0].y);
for (var j = 1; j < points[i].length; j++) {
paths[i].lineTo(points[i][j].x, points[i][j].y);
}
}
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "green";
ctx.fill(paths[paths.length - 1], 'evenodd')
ctx.stroke(paths[paths.length - 1]);
}
canvas.onmousedown = function (e) {
drawNow = true;
points.push([]);
points[points.length - 1].push({ x: e.clientX, y: e.clientY });
canvas.onmousemove = function (e) {
if (drawNow) {
points[points.length - 1].push({ x: e.clientX, y: e.clientY });
draw();
}
};
canvas.onmouseup = function () {
drawNow = false;
};
};
</script>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。