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

代码如下:

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 水印字体大小如何适配不同分辨率的图片?

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



回答:

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


回答:

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;

// 根据图片大小动态设置字体大小

const fontSize = canvas.width * 0.02; // 调整这个比例以适应你的需求

ctx.font = `${fontSize}px 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();

};

});

以上是 canvas 水印字体大小如何适配不同分辨率的图片? 的全部内容, 来源链接: utcz.com/p/934706.html

回到顶部