const watermark = require('../components/share-dialog/images/watermark.png')
export const drawWatermark = function ({
url = '', // 图片链接
textAlign = 'center', // 居中方式
textBaseline = 'middle', // 垂直居中方式
font = '23px PingFangSC-Regular', // 字体
fillStyle = 'rgba(255,255,255, 1)', // 颜色
content = '内容', // 内容
textX = 0, // X轴
textY = 30, // Y轴
logo = { w: 120, h: 30, src: watermark }, // logo宽
imgType = 'image/jpeg', // 保存类型 jpeg/png
imgQuality = 0.6 // 图片质量 0-1
} = {}) {
let img = new Image();
img.src = url.replace(
'',// 代理地址
''//前端代理地址
);
img.crossOrigin = 'anonymous';
let proms = new Promise((resolve, reject) => {
// logo
let imglogo = new Image();
imglogo.src = logo.src;
imglogo.setAttribute('crossOrigin', 'anonymous');
imglogo.onload = function() {
img.onload = function() {
let canvas = document.createElement('canvas'); // 创建canvas
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext('2d');
ctx.letterSpacingText = canvasLetterSpacing;
// 背景
ctx.drawImage(img, 0, 0, img.width, img.height);
// 动态水印
// 文字
// ctx.textAlign = textAlign;
// ctx.textBaseline = textBaseline;
// ctx.font = font;
// ctx.fillStyle = fillStyle;
// let logoFontX = img.width - (textX || img.width / 2) + (logo.w / 2)
// let logoFontY = (img.height - textY) + ((logo.h - 23) / 2) - 1
// let logoFontW = ctx.letterSpacingText(
// content,
// logoFontX,
// logoFontY,
// 2
// );
// let logoX = img.width - (textX || img.width / 2) - (logoFontW / 1.5)
// let logoY = (img.height - textY - logo.h / 2)
// 蒙层
let x1 = img.width / 2
let y1 = img.height
let x2 = img.width / 2
let y2 = img.height - 120
// x1, y1 起始坐标 x2,y2 终点坐标
let grd = ctx.createLinearGradient(x1, y1, x2, y2)
grd.addColorStop(0, 'rgba(0, 0, 0, 0.5)');
grd.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = grd;
ctx.fillRect(0, y2, img.width, 120);
// 水印图片
let logoX = img.width - (textX || img.width / 2) - (logo.w / 2)
let logoY = (img.height - textY - logo.h / 2)
ctx.drawImage(imglogo, logoX, logoY, logo.w, logo.h);
let base64Url = canvas.toDataURL(imgType, imgQuality);
resolve(base64Url)
};
img.onerror = function() {
let none = ''
reject(none)
};
}
})
return proms
}
网友评论