I am currently working on a project where users can upload an image onto an HTML5 canvas with fixed dimensions. The uploaded image can be dragged and resized using mouse input while preserving its aspect ratio. Below is the draw function I am using to achieve this:
if(image){
const scaleX = CANVAS_WIDTH / image?.width;
const scaleY = CANVAS_HEIGHT / image?.height;
const scale = Math.min(scaleX, scaleY);
// Calculate the new dimensions of the image
const newWidth = image?.width * scale;
const newHeight = image?.height * scale;
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the image on the canvas
setImageRight((CANVAS_WIDTH + newWidth) / 2);
setImageBottom((CANVAS_HEIGHT + newHeight) / 2);
ctx.drawImage(image, (CANVAS_WIDTH - newWidth) / 2, (CANVAS_HEIGHT - newHeight) / 2, newWidth, newHeight);
}
The "image" variable is part of a useState hook that I set using the following code snippet:
useEffect(() => {
const image = new Image();
image.src = URL.createObjectURL(props.imageFile);
image.onload = () => {
setImage(image);
setImageWidth(image.width);
setImageHeight(image.height);
};
}, [props.imageFile]);
useEffect(() => {
if(image)
drawImage(true,false);
}, [image])
While the aspect ratio of the initial image rendered on the canvas is preserved, the quality of the image is being significantly degraded. Are there any solutions to maintain or improve the image quality on the canvas? I have limited experience with HTML5 Canvas methods and would greatly appreciate any advice.
Edit: https://i.sstatic.net/fdRnn.jpg
https://i.sstatic.net/nVYsq.jpg
The first link shows the image I am drawing on the canvas, while the second link displays the image drawn by Photoroom on their canvas. A noticeable difference in quality can be observed despite both images and canvas having similar dimensions.