使用 signature_pad canvas 庫生成的圖片太大。但又沒有提供方法來壓縮。
當然這是根據你canvas的畫布大小決定的,某些原因導致我的畫布就得是那么大。
隨隨便便一個圖片轉化為base64 之后就是200kb-300kb。所以得想辦法壓縮。
思路就是把生成的base64 圖片再一次放入canvas 中 ,然后等比縮小4倍即可。
save () { if (this.$refs.signature.isEmpty() === false) { // https://github.com/WangShayne/vue-signature var png = this.$refs.signature.save(); this.compressedPicture(png, _ => { console.log(_); }) } }, compressedPicture (url, callback) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var img = new Image; img.onload = function(){ console.log(img.width); var width = img.width; var height = img.height; // 按比例壓縮4倍 var rate = (width < height ? width / height : height / width) / 4; canvas.width = width * rate; canvas.height = height * rate; ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate); var dataURL = canvas.toDataURL('image/jpeg'); callback.call(this, dataURL); canvas = null; console.log(dataURL); }; img.src = url },