useShapeProps.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. : fillType === "gradient"
  43. ? `url(#${id})`
  44. : fillType === "image"
  45. ? `url(#${objectFit})`
  46. : "";
  47. const defsContent = (
  48. <>
  49. {gradientType === "linear" && (
  50. <linearGradient
  51. id={id}
  52. gradientTransform={`rotate(${gradientValue})`}
  53. >
  54. <stop offset="0%" stopColor={color1} />
  55. <stop offset="100%" stopColor={color2} />
  56. </linearGradient>
  57. )}
  58. {gradientType === "radial" && (
  59. <radialGradient
  60. id={id}
  61. cx="50%"
  62. cy="50%"
  63. r={gradientValue + "%"}
  64. fx="50%"
  65. fy="50%"
  66. >
  67. <stop offset="0%" stopColor={color1} />
  68. <stop offset="100%" stopColor={color2} />
  69. </radialGradient>
  70. )}
  71. {fillType === "image" && (
  72. <pattern id={id} patternUnits="userSpaceOnUse" width="4" height="4">
  73. <image href={imageUrl} x="0" y="0" width="4" height="4"></image>
  74. </pattern>
  75. )}
  76. </>
  77. );
  78. const strokeDasharray = LineType[stroke.type];
  79. return {
  80. strokeColor: stroke.color,
  81. strokeWidth: stroke.width,
  82. fillContent,
  83. defsContent,
  84. strokeDasharray
  85. };
  86. }