DEV Community

Cover image for Convert Canvas To Image | Use with react-image-crop
Sandeep
Sandeep

Posted on

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);
    });
  }
Enter fullscreen mode Exit fullscreen mode

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);
  }
Enter fullscreen mode Exit fullscreen mode

the crop has some object

  {
    unit: "%",
    width: 30,
    height: 30,
    aspect: 1 / 1
  }
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
deepakjaiswal profile image
Sandeep

when you can use react-image-crop then its very important for everyone.