DEV Community

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

Posted on

4 1 1 1 1

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.

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (1)

Collapse
 
deepakjaiswal profile image
Deepak Jaiswal

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay