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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
deepakjaiswal profile image
Deepak Jaiswal

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay