auto-accept/www/js/svg.js

47 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-12-17 11:09:22 +00:00
function getPathShapeBetweenPoints(p1, p2, corners) {
let d = `M ${p1.x},${p1.y} L `;
if(corners == 4){
// draw inbetween p1 & p2.
d += ` ${p1.x},${p2.y} ${p2.x},${p2.y} ${p2.x},${p1.y} ${p1.x},${p1.y} `;
}
else{
// find center of circle that describes the polygon of which p1 and p2 are part
// it's _not_ the center between the two points, as p1 and p2 are corners on the shape
// distance between p1 and p2
const length = Math.sqrt(Math.pow(p1.x-p2.x,2)+ Math.pow(p1.y - p2.y, 2));
const segmentAngle = Math.PI * 2 / corners;
2020-12-17 11:12:37 +00:00
// TODO: can we find a way to draw not from the first 3 segments, but have the
// cursor span as many segment as possible
2020-12-17 11:09:22 +00:00
// const segmentsAngle = Math.floor(180/segmentAngle) * segmentAngle;
const radius = (length*.5)/Math.sin(segmentAngle);
const rotation = Math.atan2((p2.y -p1.y),(p2.x - p1.x)) + (Math.PI/2-segmentAngle);
const dx = Math.cos(rotation) * radius;// * Math.sign(p2.x - p1.x);
const dy = Math.sin(rotation) * radius;// * Math.sign(p2.y - p1.y);
// we now have the center:
const cx = p2.x - dx;
const cy = p2.y - dy;
// startpoint in relation to circle
const sx = cx - p1.x;
const sy = cy - p1.y;
let startRot = Math.asin(sx / radius);
if(sy>0){startRot = -1 * startRot + Math.PI;}
2020-12-17 11:12:37 +00:00
2020-12-17 11:09:22 +00:00
for (let a = 0; a < Math.PI*2; a += segmentAngle) {
let x = radius * Math.sin(a-startRot) + cx;
let y = radius * Math.cos(a-startRot) + cy;
d += ` ${x},${y}`;
}
}
return d + ' Z';
}
export {getPathShapeBetweenPoints};