canvas-backend/src/components/EachComponent/CustomShape/CustomShape.jsx
2025-02-11 17:55:34 +06:00

77 lines
2.3 KiB
JavaScript

import ActiveObjectContext from "@/components/Context/activeObject/ObjectContext";
import CanvasContext from "@/components/Context/canvasContext/CanvasContext";
import { useContext } from "react";
import { shapes } from "./shapes";
import { fabric } from "fabric";
import useProject from "@/hooks/useProject";
const CustomShape = () => {
const { canvas } = useContext(CanvasContext);
const { setActiveObject } = useContext(ActiveObjectContext);
const { projectData, projectUpdate, id } = useProject();
const addShape = (each) => {
// Load the SVG from the imported file
fabric.loadSVGFromURL(each, (objects, options) => {
const svgGroup = fabric.util.groupSVGElements(objects, options);
// Calculate canvas center
const centerX = canvas.getWidth() / 2;
const centerY = canvas.getHeight() / 2;
// Set properties for centering the SVG
svgGroup.set({
left: centerX, // Center horizontally
top: centerY, // Center vertically
originX: "center", // Set the origin to the center
originY: "center",
fill: "#f09b0a",
scaleX: 1,
scaleY: 1,
strokeWidth: 0,
});
// Add SVG to the canvas
canvas.add(svgGroup);
canvas.setActiveObject(svgGroup);
// Update the active object state
setActiveObject(svgGroup);
// Render the canvas
canvas.renderAll();
const object = canvas.toJSON(['id', 'selectable']);
const updateData = { ...projectData?.data, object };
// Wait for the project update before continuing
projectUpdate({ id, updateData });
});
};
return (
<div
className="rounded-md grid grid-cols-3 gap-2 p-2"
onClick={() => addShape()}
>
{shapes.map((each) => (
<div
key={each.shape}
className="relative aspect-square flex items-center justify-center bg-secondary rounded-md cursor-pointer"
onClick={(e) => {
e.stopPropagation();
addShape(each.source);
}}
>
<img
src={each.source}
alt={`Shape ${each.shape}`}
className="max-w-full max-h-full p-1 object-contain hover:bg-gray-200 rounded-md transition-colors duration-200"
/>
</div>
))}
</div>
);
};
export default CustomShape;