function transformFile(text = '', maxWidth = 600, maxHeight) {
return function (file) {
return new Promise(resolve => {
const reader = new FileReader();
reader.readAsDataURL(file);
console.log(file.size);
reader.onload = () => {
const canvas = document.createElement('canvas');
const img = new Image();
img.src = reader.result;
img.onload = () => {
var originWidth = img.width;
var originHeight = img.height;
// 目标尺寸
var targetWidth = originWidth, targetHeight = originHeight;
if (maxHeight) {
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
} else {
// 高度不存在就宽度固定,高度按比例
targetWidth = originWidth > maxWidth ? maxWidth : originWidth;
targetHeight = Math.round(targetWidth * (originHeight / originWidth));
}
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
ctx.font = maxWidth === 600 ? '20px Georgia' : '10px Georgia';
ctx.globalAlpha = 0.5;
ctx.fillStyle = '#aaaaaa';
ctx.textBaseline = 'top';
const strLen = text.length;
let h = maxWidth === 600 ? 100 : 50;
let w = maxWidth === 600 ? strLen * 30 : strLen * 20;
for (let hh = 0; hh < targetHeight; hh += h) {
for (let ww = 0; ww < targetWidth; ww += w) {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.translate(ww, hh);
ctx.rotate(-45 * Math.PI / 180);
ctx.fillText(text, 0, 0);
}
}
canvas.toBlob((blob) => {
resolve(new File([blob], file.name, { type: file.type, lastModified: Date.now() }));
// resolve(blob)
});
};
};
})
}
}
ps:readAsDataURL图片,图片会增大。
然后onload一下图片,图片月也会增大。
添加水印,图片也会增大。
出现的问题:水印位置问题。一开始我没有旋转,正常打印,发现位置正确,但是我采取了旋转(rotate),位置就和预想的不一样了。
解决问题:setTransform一下,每次旋转的中心点都重新设置下。