useShapeProps.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { ImageFillType, LineType } from "@/enum";
  2. import { uniqueId } from "lodash-es";
  3. type PropType = {
  4. fill: {
  5. fillType: "color" | "gradient" | "image";
  6. color1: string;
  7. color2: string;
  8. gradientType: "linear" | "radial";
  9. gradientValue: number;
  10. imageUrl: string;
  11. objectFit: ImageFillType.Fill;
  12. };
  13. size: {
  14. width: number;
  15. height: number;
  16. };
  17. stroke: {
  18. type: "solid" | "dashed" | "dotted" | "dashdot";
  19. color: string;
  20. width: number;
  21. };
  22. };
  23. export function useShapeProps(
  24. fill: PropType["fill"],
  25. size: PropType["size"],
  26. stroke: PropType["stroke"]
  27. ) {
  28. const {
  29. fillType,
  30. color1,
  31. color2,
  32. gradientType,
  33. gradientValue,
  34. objectFit,
  35. imageUrl,
  36. } = fill;
  37. const { width, height } = size;
  38. const id = uniqueId("fill_");
  39. const fillContent =
  40. fillType === "color"
  41. ? color1
  42. : `url(#${id})`;
  43. const defsContent = (
  44. <>
  45. {fillType === "color" && gradientType === "linear" && (
  46. <linearGradient
  47. id={id}
  48. gradientTransform={`rotate(${gradientValue})`}
  49. >
  50. <stop offset="0%" stopColor={color1} />
  51. <stop offset="100%" stopColor={color2} />
  52. </linearGradient>
  53. )}
  54. {fillType === "color" && gradientType === "radial" && (
  55. <radialGradient
  56. id={id}
  57. cx="50%"
  58. cy="50%"
  59. r={gradientValue + "%"}
  60. fx="50%"
  61. fy="50%"
  62. >
  63. <stop offset="0%" stopColor={color1} />
  64. <stop offset="100%" stopColor={color2} />
  65. </radialGradient>
  66. )}
  67. {fillType === "image" && (
  68. <pattern id={id} patternUnits="userSpaceOnUse" width={width} height={height}>
  69. <image href={imageUrl} x="0" y="0" width={width} height={height}></image>
  70. </pattern>
  71. )}
  72. </>
  73. );
  74. const strokeDasharray = LineType[stroke.type];
  75. return {
  76. strokeColor: stroke.color,
  77. strokeWidth: stroke.width,
  78. fillContent,
  79. defsContent,
  80. strokeDasharray
  81. };
  82. }