import { Canvas, Image as FabricImage, Point } from 'fabric'; // Ensure correct Fabric.js imports
// Define placeholder types if not globally available in your project
type Size = { width: number; height: number };
type Position = { x: number; y: number };
// Assume 'clipPath' and 'canvasInstance' are refs or reactive objects available in your composable scope.
// Example:
// import { ref } from 'vue';
// const clipPath = ref<Fabric.Object | null>(null); // e.g., Fabric.Path, Fabric.Rect
// const canvasInstance = ref<Fabric.Canvas | null>(null);
/**
* Exports the current Fabric.js canvas content as an image, with options for size,
* positioning, and DPI, applying a clipping path.
*
* @param outputPxSize - The desired pixel dimensions (width, height) for the exported image.
* @param designOption - Configuration options for how the design content should be placed:
* - size?: The dimensions the design content should occupy within the outputPxSize.
* If omitted, the design content scales to fit the outputPxSize while maintaining aspect ratio,
* using the original canvas dimensions as the "full size of design".
* - position?: The top-left coordinate (x, y) where the scaled design content should be placed.
* If omitted, the design content will be centered within the outputPxSize.
* - dpi?: The dots per inch for the image, used for calculating physical dimensions. Defaults to 150.
* @returns A promise resolving to an object containing the dataURL, DPI, output pixel size,
* and calculated physical size, or null if prerequisites are not met.
*/
const exportAsImg = async (
outputPxSize: Size,
designOption: {
size?: Size;
position?: Position;
dpi?: number;
} = {}, // Make designOption parameter optional
) => {
// Ensure we have the necessary fabric.js instances available
const currentClipPath = clipPath.value;
const currentCanvas = canvasInstance.value;
if (!currentClipPath || !currentCanvas) {
console.error("Fabric.js export error: Clip path or canvas instance not available.");
return null; // Indicate failure or throw an error
}
// --- 1. Determine Configuration and Defaults ---
// Use provided DPI or default to 150
const dpi = designOption.dpi || 150;
// Determine the reference size of the "design" content.
// If 'designOption.size' is not provided, use the original canvas dimensions
// as the "full size of design" to be scaled and positioned.
const originalCanvasWidth = currentCanvas.getWidth();
const originalCanvasHeight = currentCanvas.getHeight();
const designContentReferenceSize: Size = designOption.size || {
width: originalCanvasWidth,
height: originalCanvasHeight,
};
// --- 2. Calculate Scaling and Positioning ---
// Calculate the scaling factor to fit 'designContentReferenceSize' into 'outputPxSize'
// while maintaining aspect ratio. This factor is applied to all objects and the clip path.
const widthScaleRatio = outputPxSize.width / designContentReferenceSize.width;
const heightScaleRatio = outputPxSize.height / designContentReferenceSize.height;
const scaleFactor = Math.min(widthScaleRatio, heightScaleRatio);
// Calculate the position offset for the scaled design content.
// If 'designOption.position' is not provided, center the scaled design within the output canvas.
const targetPosition: Position = designOption.position || {
// Calculate the top-left corner (x, y) of the scaled design's bounding box
// to center it within the outputPxSize canvas.
x: (outputPxSize.width - designContentReferenceSize.width * scaleFactor) / 2,
y: (outputPxite.height - designContentReferenceSize.height * scaleFactor) / 2,
};
// --- 3. Create Output Canvas with Transformed Clip Path ---
// Clone the original clipPath object and apply the calculated transformations.
const transformedClipPath = await currentClipPath.clone();
transformedClipPath.set({
// Apply scale and position to the clipPath object itself.
left: (currentClipPath.left || 0) * scaleFactor + targetPosition.x,
top: (currentClipPath.top || 0) * scaleFactor + targetPosition.y,
scaleX: (currentClipPath.scaleX || 1) * scaleFactor,
scaleY: (currentClipPath.scaleY || 1) * scaleFactor,
// Ensure no nested clip paths interfere.
clipPath: null,
});
// Create the new canvas instance with the output dimensions and the transformed clip path.
const outputCanvas = new Canvas("", {
width: outputPxSize.width,
height: outputPxSize.height,
clipPath: transformedClipPath, // Apply the transformed clip path to the entire canvas
});
// --- 4. Process and Transform Design Objects ---
const originalObjects = currentCanvas.getObjects() || [];
for (const obj of originalObjects) {
// Clone each object to avoid modifying the original canvas's state.
const clonedObj = await obj.clone();
// Apply the same scaling and positioning transformations to each cloned object.
clonedObj.set({
noScaleCache: true, // Performance optimization
objectCaching: false, // Performance optimization
// Apply the calculated scale factor to the object's existing scale.
scaleX: (obj.scaleX || 1) * scaleFactor,
scaleY: (obj.scaleY || 1) * scaleFactor,
// Apply the calculated position offset.
left: ((obj.left || 0) * scaleFactor) + targetPosition.x,
top: ((obj.top || 0) * scaleFactor) + targetPosition.y,
// Remove any pre-existing clip paths from individual objects;
// they should only be clipped by the main outputCanvas clip path.
clipPath: null,
});
// Add the transformed object to the output canvas.
outputCanvas.add(clonedObj);
}
// --- 5. Export the Canvas ---
// Render the output canvas to a data URL.
const dataURL = outputCanvas.toDataURL({
format: "jpeg", // Or 'png' as needed
quality: 1, // Maximum quality for JPEG
multiplier: 1, // Use 1 as objects are already scaled
});
// --- 6. Cleanup and Return ---
// Dispose of the temporary output canvas to free memory.
outputCanvas.dispose();
// Optionally, trigger a download for testing (as in original code).
const link = document.createElement("a");
link.download = `exported-image-${outputPxSize.width}x${outputPxSize.height}@${dpi}dpi.jpeg`;
link.href = dataURL;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Calculate and return physical size in cm and inches.
const physicalSizeCm = {
width: (outputPxSize.width / dpi) * 2.54,
height: (outputPxSize.height / dpi) * 2.54,
};
const physicalSizeIn = {
width: outputPxSize.width / dpi,
height: outputPxSize.height / dpi,
};
// Return the export results.
return {
dataURL,
dpi,
outputPxSize,
physicalSize: { cm: physicalSizeCm, inches: physicalSizeIn },
};
};