前端上传图片压缩并添加水印

<input type="file" class="upload" accept="image/*">
<div class="div"></div>
<script>

    document.querySelector('.upload').addEventListener('change', function () {

        var file = this.files;

        var reader = new FileReader();

        reader.readAsDataURL(file[0]);

        reader.onloadend = function () {

            var src = this.result;   //result为data url的形式

            var img = new Image();

            img.src = src;

            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.font = '100px simsun'
                ctx.fillText('www.blyoo.com', 5, 100);


                //返回图片类型 webp 或者 jpeg
                var newImg = canvas.toDataURL('image/jpeg', 0.5);//压缩0.5比例 ,0-1区间

                console.log(newImg);



            }

        }

    })
</script>

看演示

图片并没有上传到后端,只是前端压缩后展示出来

查看演示