; const h = Number(document.getElementById('crop-h').value) * displayScale; const c = document.getElementById('crop-canvas'); cropRect = { x: Math.max(0, Math.min(c.width - 10, x)), y: Math.max(0, Math.min(c.height - 10, y)), w: Math.max(10, Math.min(c.width - x, w)), h: Math.max(10, Math.min(c.height - y, h)), }; renderCropUI(); } function cropAndDownload() { if (!sourceImg) return; const s = 1 / displayScale; const sx = cropRect.x * s, sy = cropRect.y * s; const sw = cropRect.w * s, sh = cropRect.h * s; const c = document.createElement('canvas'); c.width = sw; c.height = sh; c.getContext('2d').drawImage(sourceImg, sx, sy, sw, sh, 0, 0, sw, sh); const mime = outFmt || (sourceFile ? sourceFile.type : 'image/jpeg'); const ext = mime.split('/')[1] === 'jpeg' ? 'jpg' : mime.split('/')[1]; c.toBlob(blob => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = (sourceFile ? sourceFile.name.replace(/\.[^.]+$/, '') : 'cropped') + '-cropped.' + ext; a.click(); URL.revokeObjectURL(a.href); showToast('Photo cropped and downloaded!', 'success'); }, mime, 0.92); } document.addEventListener('DOMContentLoaded', () => { if (window.lucide) lucide.createIcons(); });