根据父图像缩放图像。

huangapple go评论48阅读模式
英文:

Scale Image based on parent Image

问题

这是标志

根据父图像缩放图像。

这是我得到的结果

根据父图像缩放图像。

英文:

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
根据父图像缩放图像。

this is the result i get 根据父图像缩放图像。

答案1

得分: 1

你可以使用 object-fit CSS 属性将标志图像缩放为父元素宽度的四分之一,高度将自动调整而不会损失图像质量。

了解有关 object-fit 的更多信息 点击这里

英文:

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 abject fit here.

答案2

得分: 0

当你在画布中进行图像缩放时,应始终像下面这样四舍五入值。

你不能使用小数来表示画布的大小,因为像素是整数1px大小的!

此外,你不需要创建不必要的变量,比如maxWidth。

总之,用这个替换所有这些:

//定义图像比例
var ratio = logo.width / logo.height;

let maxWidth = target.width / 4;
let maxHeight = (target.width / 4) * ratio;

img.width = maxWidth;
img.height = maxHeight;

只用这个:

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

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

注意:你两次使用了target.width

英文:

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!

huangapple
  • 本文由 发表于 2023年6月15日 16:54:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定