<!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>
<script src="./fabric.js"></script>
<style>
button {
margin: 10px 0 0 10px;
}
</style>
</head>
<body>
<div style="display: flex;">
<canvas id='c' width="1000" height="1000"></canvas>
<div>
<button class="btn1">画</button>
<button class="btn2">儿子</button>
</div>
</div>
<script>
var canvas = new fabric.Canvas('c', {
backgroundColor: '#ccc',
selectionColor: 'white',
selectionLineWidth: 2,
selectionBorderColor: 'red',
borderColor: 'red'
});
function addRing(angle1, angle2, x, y, r1, r2) {
let point1 = {};
let point2 = {};
let point3 = {};
let point4 = {};
let isBig = 0
angle1 = angle1 % 360;
angle2 = angle2 % 360;
if (angle2 > 180) {
isBig = 1
}
if (!angle2) {
point1.x = r1 + x;
point1.y = y;
point2.x = r2 + x;
point2.y = y;
var path = new fabric.Path(`M${point1.x},${point1.y} A${r1},${r1} 0 0,1 ${point1.x - 2 * r1},${point1.y}
A${r1},${r1} 0 0,1 ${point1.x},${point1.y}
M${point2.x},${point2.y} A${r2},${r2} 0 0,1 ${point2.x - 2 * r2},${point2.y}
A${r2},${r2} 0 0,1 ${point2.x},${point2.y}`, {
stroke: 'red',
fill: 'transparent',
hasControls: false
})
} else {
point1.x = r1 * Math.cos(angle1 / 180 * Math.PI) + x;
point1.y = r1 * Math.sin(angle1 / 180 * Math.PI) + y;
point2.x = r2 * Math.cos(angle1 / 180 * Math.PI) + x;
point2.y = r2 * Math.sin(angle1 / 180 * Math.PI) + y;
point3.x = r2 * Math.cos((angle1 + angle2) / 180 * Math.PI) + x;
point3.y = r2 * Math.sin((angle1 + angle2) / 180 * Math.PI) + y;
point4.x = r1 * Math.cos((angle1 + angle2) / 180 * Math.PI) + x;
point4.y = r1 * Math.sin((angle1 + angle2) / 180 * Math.PI) + y;
var path = new fabric.Path(`M${point1.x},${point1.y} L${point2.x},${point2.y} A${r2},${r2} 0 ${isBig},1 ${point3.x},${point3.y} L${point4.x},${point4.y} A${r1},${r1} 0 ${isBig},0 ${point1.x},${point1.y}`, {
stroke: 'red',
fill: 'transparent',
// hasControls: false
})
}
// path.parmas={
// angle1, angle2, x, y, r1, r2
// }
// canvas.loadFromJSON({
// objects:[ path.toJSON()]
// })
canvas.add(path)
// canvas.add( fabric.fromObject(path.toJSON()))
}
addRing(0, 300, 400, 200, 30, 60);
addRing(0, 360, 200, 200, 30, 60);
addRing(0, 280, 600, 200, 60, 60)
</script>
</body>
</html>
addPath 参数说明 angle1, angle2, x, y, r1, r2 分别对应 偏转角度,弧形区域的角度,x,y是圆心,r1小圆半径,r2大圆半径。
fabric.js我是引用的本地的文件,记得修改路径。
效果图