<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>水印</title>
</head>
<body>
<input type="file" onchange="loadImg(this)">
<img src="" alt="">
<canvas></canvas>
<script>
// 上传图片
function loadImg(me) {
let img = document.querySelector('img');
let cvs = document.querySelector('canvas');
let file = me.files[0]; // 获取到文件对象
console.log(file)
// 上传的图片大于 500KB 时才压缩
if (file && (file.size / 1024 > 60)) {
console.log("666")
let reader = new FileReader();
reader.readAsDataURL(file); // 转成 base64 编码
reader.onload = function (e) {
let naturalBase64 = e.target.result; // 获取 base64 编码,这是原图的
img.src = naturalBase64;
img.onload = function () {
let ratio = img.naturalWidth / img.naturalHeight; // 获取原图比例,为了等比压缩
cvs.width = 400;
cvs.height = cvs.width / ratio;
let ctx = cvs.getContext('2d');
ctx.drawImage(img, 0, 0, cvs.width, cvs.height); // 画在 canvas 上
ctx.font="20px microsoft yahei";
let gradient=ctx.createLinearGradient(0,0,cvs.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
ctx.fillStyle=gradient;
ctx.fillText("少时诵诗书",10,30);
// 压缩后新图的 base64
let zipBase64 = cvs.toDataURL();
}
}
}
}
</script>
</body>
</html>