base64图片使用canvas剪切压缩后,生成的base64图像,预览为什么会有一部分是黑色

使用如下函数压缩图片
输入参数path:base64
回调函数输出也是 base64
但是预览图片刚上传时偶尔会出现一部分黑色或全黑。
偶尔剪切时也有这种情况
缩放一下裁剪框,才会正常
image.png
求大神指教~~

  dealImg: function(path, obj, callback) {
                    let ts = this;
                    var img = new Image();
                    img.src = path;
                    img.onload = function() {
                        var that = this;
                        // 默认按比例压缩
                        var w = that.width,
                            h = that.height,
                            scale = w / h;
                        w = obj.width || (obj.height * scale);
                        h = obj.height || (obj.width / scale);
                        w=Math.round(w)
                        h=Math.round(h)
                        var quality = 0.7; // 默认图片质量为0.7
                        //生成canvas
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 创建属性节点
                        var anw = document.createAttribute("width");
                        anw.nodeValue = w;
                        ts.rw = w;
                        var anh = document.createAttribute("height");
                        anh.nodeValue = h;
                        ts.rh = h;
                        canvas.setAttributeNode(anw);
                        canvas.setAttributeNode(anh);
                        ctx.drawImage(that, 0, 0, w, h);
                        // 图像质量
                        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                            quality = obj.quality;
                        }
                        // quality值越小,所绘制出的图像越模糊
                        var base64 = canvas.toDataURL('image/jpeg', quality); // base64 格式
                        // 回调函数返回base64的值
                        callback(base64);
                    }
          },
```~~~~

代码参考:https://blog.csdn.net/baidu_2...

阅读 3.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题