图片上传时用Canvas 压缩和加水印

用菜鸟教程模拟的

菜鸟对应链接 https://www.runoob.com/try/try-cdnjs.php?filename=tryhtml5_canvas_tut_img

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
</head>
<body>

<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277"><p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。</canvas>
<img id="screamaa" src="" alt="The Scream" width="220" height="277">
      <input type="file"
              id="uploadFile"
              accept="image/*"
            />
<script>

var imgff= function (base64){
      var bili = 0.7; //压缩后的图片尺寸,0.7就是70%
     
var img=new Image() 
img.src = base64
    console.log("img.width", img.width,"height", img.height)
img.onload = function() {
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
      //图片地址加载完后执行操作
        var newWidth = img.width; //压缩后图片的宽度
        var newHeight = img.height; //压缩后图片的高度
        c.width = newWidth; //压缩图的宽度
        c.height = newHeight; //压缩图的高度
        ctx.drawImage(img, 0, 0, newWidth,newHeight); //压缩 把图片放到画布上
    
    ctx.font="30px Arial";
    ctx.fillStyle = "#ffffff"; //设置水印
    ctx.fillText("你好", 40, 40); //选择水印位置
    
    
    let newBase64 = c.toDataURL("image/jpeg", 0.7);
    console.log("dnewBase64",newBase64)
    var c=document.getElementById("screamaa");
    c.src =newBase64
} 
}

 var eleUploadFile = document.getElementById('uploadFile');
    
   eleUploadFile.addEventListener('change', function(event) {
        var file = event.target.files[0] || event.target.dataTransfer.files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            var base64 = e.target.result;
            // canvas压缩图片,并且回调显示
            imgff(base64)
        }
        reader.readAsDataURL(file);
    });

</script>

</body>
</html>

 

posted @ 2020-12-24 17:10  路过春天的雨点  阅读(186)  评论(0)    收藏  举报