From 146921ad81b5f3a8ecfc3156c317b30193a2aca5 Mon Sep 17 00:00:00 2001 From: Valentin Hervieu Date: Sat, 8 Feb 2020 13:10:53 +0100 Subject: [PATCH] Use smaller canvas for crop demo --- docs/src/components/Demo/cropImage.ts | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/docs/src/components/Demo/cropImage.ts b/docs/src/components/Demo/cropImage.ts index 734988a..e98b4f5 100644 --- a/docs/src/components/Demo/cropImage.ts +++ b/docs/src/components/Demo/cropImage.ts @@ -20,31 +20,42 @@ export default async function getCroppedImg( imageSrc: string, pixelCrop: Area, rotation = 0 -): Promise { +): Promise { const image = await createImage(imageSrc) const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') + if (!ctx) { + return null + } + + const maxSize = Math.max(image.width, image.height) + const safeArea = 2 * ((maxSize / 2) * Math.sqrt(2)) + // set width to double image size to allow for a safe area for the // image to rotate in without being clipped by canvas context - canvas.width = image.width * 2 - canvas.height = image.height * 2 + canvas.width = safeArea + canvas.height = safeArea // translate canvas context to a central location to allow rotating around the center. - ctx.translate(image.width, image.height) + ctx.translate(safeArea / 2, safeArea / 2) ctx.rotate(getRadianAngle(rotation)) - ctx.translate(-image.width, -image.height) + ctx.translate(-safeArea / 2, -safeArea / 2) // draw rotated image and store data. - ctx.drawImage(image, image.width / 2, image.height / 2) - const data = ctx.getImageData(0, 0, image.width * 2, image.height * 2) + ctx.drawImage(image, safeArea / 2 - image.width * 0.5, safeArea / 2 - image.height * 0.5) + const data = ctx.getImageData(0, 0, safeArea, safeArea) // set canvas width to final desired crop size - this will clear existing context canvas.width = pixelCrop.width canvas.height = pixelCrop.height // paste generated rotate image with correct offsets for x,y crop values. - ctx.putImageData(data, 0 - image.width / 2 - pixelCrop.x, 0 - image.height / 2 - pixelCrop.y) + ctx.putImageData( + data, + 0 - safeArea / 2 + image.width * 0.5 - pixelCrop.x, + 0 - safeArea / 2 + image.height * 0.5 - pixelCrop.y + ) // As Base64 string // return canvas.toDataURL('image/jpeg');