英文:
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;
};
}
答案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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论