图片加水印
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>图片加水印</title>
<script>
window.onload = () => {
document.getElementById("submitSelectedFilesBtn").onclick = (event) => {
document.getElementById("outputArea").innerHTML = "";
var watermarkText = document.getElementById("watermarkText").value;
var fontSize = document.getElementById("fontSize").value;
var fontAlpha = document.getElementById("fontAlpha").value;
var selectedFilesInput = document.getElementById("selectedFilesInput");
for (let i = 0; i < selectedFilesInput.files.length; i++) {
let file = selectedFilesInput.files[i];
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.onload = function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
ctx.rotate(45 * Math.PI / 180);
ctx.fillStyle = "grey";
ctx.font = fontSize + "px Arial";
ctx.globalAlpha = fontAlpha;
let startX = 0 - canvas.width;
let startY = 0 - canvas.height;
let step = Math.sqrt(Math.pow(watermarkText.length * fontSize, 2) + Math.pow(fontSize, 2));
while (true) {
if (startX >= canvas.width * 2) {
startX = 0;
startY += step;
}
if (startY >= canvas.height * 2) {
break;
}
ctx.fillText(watermarkText, startX, startY);
startX += step;
}
var imgOut = document.createElement("img");
imgOut.src = canvas.toDataURL();
document.getElementById("outputArea").appendChild(imgOut);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
}
}
</script>
</head>
<body>
<div>
选择图片(可多选):<input type="file" multiple="multiple" id="selectedFilesInput" /><br />
文本大小(单位固定为像素):<input type="number" value="12" id="fontSize" /><br />
水印透明度(0~1):<input style="width:5em" type="number" step="0.1" min="0" max="1" value="0.5" id="fontAlpha" /><br />
水印文字:<input type="text" value="仅供XXXXXXXXXXXXXX使用,他用无效。" id="watermarkText" /><button id="submitSelectedFilesBtn">确认</button>
</div>
<div id="outputArea"></div>
</body>
</html>