brush.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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: top - borderWidth,
  73. left: left - borderWidth,
  74. width: right - left + borderWidth * 2,
  75. height: bottom - top + borderWidth * 2,
  76. };
  77. };
  78. export const calcViewBox = (
  79. { top, left, width, height }: HTMLCoordinateType,
  80. borderWidth: number,
  81. ): string => {
  82. return `
  83. ${left} ${top} ${width + borderWidth} ${height + borderWidth}
  84. `;
  85. };