canvas-backend/src/components/EachComponent/CustomShape/CustomShape.jsx
2024-12-25 18:13:00 +06:00

68 lines
No EOL
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';
const CustomShape = () => {
const { canvas } = useContext(CanvasContext);
const { setActiveObject } = useContext(ActiveObjectContext);
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,
});
// Add SVG to the canvas
canvas.add(svgGroup);
canvas.setActiveObject(svgGroup);
// Update the active object state
setActiveObject(svgGroup);
// Render the canvas
canvas.renderAll();
});
};
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