brush.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. type Coordinates = {
  2. x: number | null;
  3. y: number | null;
  4. };
  5. type CreatePolylineType = (
  6. penCoordinates: Coordinates,
  7. color: string,
  8. opacity: number,
  9. strokeWidth: number,
  10. ) => SVGPolylineElement;
  11. type CompletePathType = (
  12. pathElement: SVGPolylineElement | null,
  13. penCoordinates: Coordinates,
  14. ) => void;
  15. export const createPolyline: CreatePolylineType = (
  16. penCoordinates,
  17. color,
  18. opacity,
  19. strokeWidth,
  20. ) => {
  21. const path = document.createElementNS(
  22. 'http://www.w3.org/2000/svg',
  23. 'polyline',
  24. );
  25. path.setAttribute('fill', 'none');
  26. path.setAttribute('stroke', color);
  27. path.setAttribute('stroke-width', strokeWidth.toString());
  28. path.setAttribute('stroke-opacity', (opacity * 0.01).toString());
  29. path.setAttribute('points', `${penCoordinates.x},${penCoordinates.y}`);
  30. return path;
  31. };
  32. export const completePath: CompletePathType = (pathElement, penCoordinates) => {
  33. if (pathElement && penCoordinates.x) {
  34. let points = pathElement.getAttribute('points') || '';
  35. points += ` ${penCoordinates.x},${penCoordinates.y}`;
  36. pathElement.setAttribute('points', points);
  37. }
  38. };
  39. export const pointCalc = (
  40. _points: PointType[][],
  41. h: number,
  42. s: number,
  43. ): PointType[][] => {
  44. const reducer = _points.reduce(
  45. (acc: PointType[][], cur: PointType[]): PointType[][] => {
  46. const p = cur.map((point: PointType) => ({
  47. x: point.x * s,
  48. y: h - point.y * s,
  49. }));
  50. acc.push(p);
  51. return acc;
  52. },
  53. [],
  54. );
  55. return reducer;
  56. };
  57. export const rectCalcWithPoint = (
  58. pointsGroup: PointType[][],
  59. borderWidth: number,
  60. ): HTMLCoordinateType => {
  61. const xArray: number[] = [];
  62. const yArray: number[] = [];
  63. pointsGroup[0].forEach((point: PointType) => {
  64. xArray.push(point.x);
  65. yArray.push(point.y);
  66. });
  67. const top = Math.min(...yArray);
  68. const left = Math.min(...xArray);
  69. const bottom = Math.max(...yArray);
  70. const right = Math.max(...xArray);
  71. return {
  72. top,
  73. left,
  74. width: right - left + borderWidth,
  75. height: bottom - top + borderWidth,
  76. };
  77. };
  78. export const calcViewBox = (
  79. { top, left, width, height }: HTMLCoordinateType,
  80. borderWidth: number,
  81. ): string => {
  82. const distance = borderWidth / 2;
  83. return `
  84. ${left - distance} ${top - distance} ${width + distance} ${height + distance}
  85. `;
  86. };