Convert Canvas To Image | Use with react-image-crop

convert-canvas-to-image-|-use-with-react-image-crop

sometime we can show data source of image show in canvas do activity like graphics design or like crop image then we need to convert canvas to image. in this example we crop a image

const TO_RADIANS = Math.PI / 180;
export function getCroppedImg(image, crop, fileName) {
    const canvas = document.createElement("canvas");
    let scale = 1;
    let rotate = 0;
    const ctx = canvas.getContext('2d')

    if (!ctx) {
      throw new Error('No 2d context')
    }

    const scaleX = image.naturalWidth / image.width
    const scaleY = image.naturalHeight / image.height
    const pixelRatio = window.devicePixelRatio
    canvas.width = Math.floor(crop.width * scaleX * pixelRatio)
    canvas.height = Math.floor(crop.height * scaleY * pixelRatio)
    ctx.scale(pixelRatio, pixelRatio)
    ctx.imageSmoothingQuality = 'high'
    const cropX = crop.x * scaleX
    const cropY = crop.y * scaleY

    const rotateRads = rotate * TO_RADIANS
    const centerX = image.naturalWidth / 2
    const centerY = image.naturalHeight / 2
    ctx.save()
    ctx.translate(-cropX, -cropY)
    ctx.translate(centerX, centerY)
    ctx.rotate(rotateRads)
    ctx.scale(scale, scale)
    ctx.translate(-centerX, -centerY)
    ctx.drawImage(
      image,
      0,
      0,
      image.naturalWidth,
      image.naturalHeight,
      0,
      0,
      image.naturalWidth,
      image.naturalHeight,
    )
    return new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        blob.name = fileName;
        resolve(blob);
      }, 'image/jpeg', 1);
    });
  }

this is main function to get image file from image ref

  const save = async () => {
    setIsLoading(true)
    let image = document.getElementById('crop-image')
    let file = await getCroppedImg(image, crop, filename);
    await changeAvatar(file);
  }

the crop has some object

  {
    unit: "%",
    width: 30,
    height: 30,
    aspect: 1 / 1
  }

when we use any crop library like react-image-crop it gives crop values of object then need to how to get cropped image then it helps to find exact image as your need.

In this example we sure to understand how we convert canvas as in image. and use it. thank you.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
the-paradox-of-ai:-we-need-to-more-of-a-human-touch-in-marketing

The Paradox of AI: We Need To More Of A Human Touch in Marketing

Next Post
content-marketing-vs.-ppc:-what-delivers-better-roi?

Content Marketing Vs. PPC: What Delivers Better ROI?

Related Posts