I have an Two Images a parrent Image (target) and a child Image (logo), I would like to scale the logo image to be 1/4th of the parent width, the height should adjust without losing the quality of the child
resizeWaterMark(config) {
return (target, logo) => {
var context = target.getContext('2d');
context.save();
context.globalAlpha = config.opacity / 100;
var img = new Image();
//Define image ratio
var ratio = logo.width / logo.height;
let maxWidth = target.width / 4;
let maxHeight = (target.width / 4) * ratio;
img.width = maxWidth;
img.height = maxHeight;
img.onload = function () {
ctx.drawImage(img);
};
img.src = URL.create;
let { x, y } = this.getWaterMarkPositionXY(target, img, config);
context.drawImage(logo, x, y, img.width, img.height);
context.restore();
return target;
};
}
2
Answers
you can use the
object-fit
CSS property to scale the logo image to 1/4th of the parent width, and the height will adjust automatically without losing the quality of the image.READ MORE ABOUT OBJECT FIT HERE :
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
When you DIVIDE to scale images in canvas, you should always round-off the values like below.
You can’t have fractions for the size of the canvas since the pixel is a whole 1px in size!
Also, you don’t need to create unnecessary variables like maxWidth.
Anyways, to cut a long story short replace all this:
…with just this:
NB: You had target.width two times!