canvas 水印字体大小如何适配不同分辨率的图片?

作者站长头像
站长
· 阅读数 20

代码如下:

return new Promise((resolve) => {
    const img = new Image();
    img.src = item.url;

    // 等待图片加载完成后绘制水印
    img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 图片压缩
        const rate = (img.width < img.height ? img.width / img.height : img.height / img.width) / 2;
        canvas.width = img.width * rate;
        canvas.height = img.height * rate;
        ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width * rate, img.height * rate);

        // 添加水印
        const watermarkText = that.getWatermarkText();
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.shadowColor = 'rgba(0, 0, 0, 0.8)';
        ctx.shadowOffsetX = 1;
        ctx.shadowOffsetY = 1;
        ctx.font = '26px Arial';
        ctx.textAlign = 'left';
        ctx.textBaseline = 'bottom';
        ctx.fillText('时间:'+ watermarkText, 10, img.height* rate - 10);
        ctx.fillText('地址:地址地址1111', 10, img.height * rate - 40);
        ctx.fillText('纬度:纬度纬度纬度1', 10, img.height * rate - 70);
        ctx.fillText('经度:经度经度经度', 10, img.height * rate - 100);
        
        resolve();
    };
});

目前效果图为(2个图的分辨率不一样):canvas 水印字体大小如何适配不同分辨率的图片?canvas 水印字体大小如何适配不同分辨率的图片?

期望:不同分辨率图片的水印字体大小一致。


回复
1个回答
avatar
test
2024-06-29

用宽度计算一下当字体大小,这样不就能保证不管多大的图,都是和宽度等比例的吗

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容