canvas将图片转成base64格式 以及 验证图片是否透明
logoImgUpload:function(file) { let self = this; self.formatUpload(file); let reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { var img = new Image(); img.src = e.target.result; self.isAlphaBackground = false; // 缩放图片需要的canvas var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); // base64地址图片加载完毕后 img.onload = function () { // 图片原始尺寸 var originWidth = this.width; var originHeight = this.height; // canvas尺寸设置 canvas.width = originWidth; canvas.height = originHeight; // 清除画布 context.clearRect(0, 0, originWidth, originHeight); // 图片绘制在画布上 context.drawImage(img, 0, 0); // 获取图片像素信息 var imageData = context.getImageData(0, 0, originWidth, originHeight).data; // 检测有没有透明数据 self.isAlphaBackground = false; for (var index = 3; index < imageData.length; index += 4) { if (imageData[index] != 255) { self.isAlphaBackground = true; break; } } // isAlphaBackground就是最后石头有透明或半透明背景色的结果 console.log(self.isAlphaBackground) }; self.design.logo = e.target.result; } return false; },