Skip to content

Commit

Permalink
Use smaller canvas for crop demo
Browse files Browse the repository at this point in the history
  • Loading branch information
ValentinH committed Feb 8, 2020
1 parent bb59cd6 commit 146921a
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions docs/src/components/Demo/cropImage.ts
Expand Up @@ -20,31 +20,42 @@ export default async function getCroppedImg(
imageSrc: string,
pixelCrop: Area,
rotation = 0
): Promise<string> {
): Promise<string | null> {
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');
Expand Down

0 comments on commit 146921a

Please sign in to comment.