import store from '@/store'
import { parseTime } from '@/utils/index'
/**
* 画布添加水印
* @param {Object} ctx
* @param {Number} imgWidth
* @param {Number} imgHeight
* @param {Object} config config.font:字体;config.textArray: ['张三','2021/11/26 16:44'], 水印文本内容,允许数组最大长度3 即:3行水印;config.density 密度 建议取值范围1-5 值越大,水印越多,可能会导致水印重叠等问题,慎重!!!
*/function drawWatermark(ctx, imgWidth, imgHeight, config) {
if (typeof ctx !== 'object' || typeof imgWidth !== 'number' || typeof imgHeight !== 'number' || typeof config !== 'object') {
throw new Error('Invalid arguments provided.');
}
const defaultConfig = {
font: 'microsoft yahei',
density: 3
};
const watermarkConfig = Object.assign({}, defaultConfig, config);
if (!watermarkConfig.font || typeof watermarkConfig.density !== 'number' || watermarkConfig.density <= 0) {
throw new Error('Invalid configuration values.');
}
const fontSize = imgWidth >= imgHeight ? Math.floor(imgWidth/40) : Math.floor(imgHeight/40);
ctx.font = `${fontSize}px ${watermarkConfig.font}`;
ctx.lineWidth = 1;
// ctx.fillStyle = 'rgba(225,73,73,0.5)';
ctx.fillStyle = 'rgba(200, 200, 200, 0.85)'
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
const maxDimension = Math.max(imgWidth, imgHeight);
const stepSize = Math.floor(maxDimension / watermarkConfig.density);
const xPositions = [0];
while (xPositions[xPositions.length - 1] < maxDimension / 2) {
xPositions.push(xPositions[xPositions.length - 1] + stepSize);
}
xPositions.push(...xPositions.slice(1, xPositions.length).map((pos) => -pos));
for (let i = 0; i < xPositions.length; i++) {
for (let j = 0; j < xPositions.length; j++) {
ctx.save();
ctx.translate(imgWidth / 2, imgHeight / 2);
ctx.rotate(-Math.PI / 5);
if (watermarkConfig.textArray.length > 3) {
watermarkConfig.textArray = watermarkConfig.textArray.slice(0, 3);
}
watermarkConfig.textArray.forEach((text, index) => {
const verticalOffset = fontSize * index + 2;
ctx.fillText(text, xPositions[i], xPositions[j] + verticalOffset);
});
ctx.restore();
}
}
}
/**
* 添加水印
* @param {String} imageUrl 图片地址
* @param {String} watermarkText 水印文本
*/
function addWatermarkToImage(imageUrl, watermarkText) {
// console.log('addWatermarkToImage', imageUrl)
let resultUrl
try {
return new Promise((resolve, reject) => {
const img = new Image()
img.src = imageUrl
img.onload = () => {
// console.log('img.onload')
const canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
const dlrCode = store.getters.dlrCode || 'null'
const userName = store.getters.userName || 'null'
const defaultText = dlrCode + '-' + userName + '-' + parseTime(new Date(), '{y}{m}{d}')
drawWatermark(ctx, img.width, img.height, {
textArray: [watermarkText || defaultText]
})
canvas.toBlob(blob => {
resultUrl = URL.createObjectURL(blob)
return resolve(resultUrl)
})
}
img.onerror = () => {
console.error('加载图片失败')
return resolve(imageUrl)
}
})
} catch (error) {
console.error('添加水印失败:', error)
} finally {
if (resultUrl) {
URL.revokeObjectURL(resultUrl)
}
}
}
export {
addWatermarkToImage
}