求助:将Logo缩至父图像1/4宽度时高度比例异常的问题
问题描述
我有两张图像:父图像(target)与子图像(Logo)。需求为将Logo缩放至父图像宽度的1/4,高度按比例自适应且不损失Logo画质,但当前实现后宽度正常,高度却不符合预期。
实现代码
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; }; }
Logo原图

当前效果截图

问题分析与修复
核心问题:比例计算逻辑错误
你当前的比例计算是ratio = logo.width / logo.height,后续用maxHeight = maxWidth * ratio会把高度过度放大,正确的高度计算应该是基于原图宽高比反向推导:
缩放后高度 = 目标宽度 × (原图高度 / 原图宽度)
其他冗余/错误代码
- 无需创建新的
Image对象:你已经拿到了加载完成的logo实例,新创建的img不仅没实际作用,还存在img.src = URL.create这种语法错误。 onload回调里的ctx未定义,且整个回调逻辑对最终绘制没有帮助。
修复后的代码
resizeWaterMark(config) { return (target, logo) => { const context = target.getContext('2d'); context.save(); context.globalAlpha = config.opacity / 100; // 计算正确的缩放尺寸 const maxWidth = target.width / 4; const maxHeight = maxWidth * (logo.height / logo.width); const { x, y } = this.getWaterMarkPositionXY(target, { width: maxWidth, height: maxHeight }, config); // 直接用原logo实例绘制,传入计算好的宽高 context.drawImage(logo, x, y, maxWidth, maxHeight); context.restore(); return target; }; }
修复说明
- 基于原图宽高比重新计算缩放后高度,保证Logo比例正确
- 移除无用的
Image对象创建逻辑,消除语法错误 - 直接使用计算后的宽高绘制Logo,逻辑更简洁
内容的提问来源于stack exchange,提问作者Suliman Noor
相关产品推荐
相关产品推荐

