Convert Canvas To Image | Use with react-image-crop
Sandeep
Posted on January 20, 2023
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.
💖 💪 🙅 🚩
Sandeep
Posted on January 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript "Master JavaScript Hoisting: 10 Tricky Output Questions Every Developer Must Know!" Part 1
October 4, 2024