xpaintdev / utils /canvasUtils.ts
suisuyy
Initialize xpaintai project with core files and basic structure
763be49
export const getBlankCanvasDataURL = (width: number, height: number): string => {
const tempCanvas = document.createElement('canvas');
tempCanvas.width = width;
tempCanvas.height = height;
const ctx = tempCanvas.getContext('2d');
if (ctx) {
ctx.fillStyle = '#FFFFFF'; // Ensure blank canvas is white
ctx.fillRect(0, 0, width, height);
}
return tempCanvas.toDataURL('image/png');
};
export const dataURLtoBlob = async (dataurl: string): Promise<Blob> => {
const res = await fetch(dataurl);
return res.blob();
};
export const calculateSHA256 = async (blob: Blob): Promise<string> => {
const buffer = await blob.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
};
export const copyToClipboard = async (
text: string,
showInfoToast: (message: string, type: 'info' | 'error') => void // Callback for toast
): Promise<boolean> => {
if (!navigator.clipboard) {
showInfoToast('Clipboard API not available.', 'info');
return false;
}
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
console.error('Failed to copy text: ', err);
showInfoToast('Failed to copy URL to clipboard.', 'error');
return false;
}
};