skip to Main Content

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;
            };
        }

this is the logo
The result i got widht is fine but height it not

this is the result i get enter image description here

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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:

    //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;
    

    …with just this:

    img.width = Math.round(target.width/4);
    
    img.height = Math.round(target.height/4);
    

    NB: You had target.width two times!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search