Skip to content

InvalidStateError: The object is in an invalid state. #8

@007sair

Description

@007sair

你好,我在使用插件的过程中遇到一个问题。如下:

环境
iPhone8 ios v11.3
微信浏览器 v6.7.1

问题描述

// 会报错:
InvalidStateError: The object is in an invalid state. /js/index.js:21:202609 drawImage@[native code]
onload@http:xxxx

伪代码如下

import 'canvasResize.js'

// 微信上传
fileUpload() {
    let me = this
    wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], 
        sourceType: ['album', 'camera'], 
        success: function (res) {
            wx.getLocalImgData({
                localId: res.localIds[0],
                success: function (res) {
                    let localData = res.localData;
                    localData = localData.replace('jgp', 'jpeg');
                    
                    let _file = file.dataURL2blob(localData)

                    canvasResize(_file, {
                        width: 1000,
                        crop: false, // 是否裁剪
                        quality: 0.9, // 压缩质量  0 - 1
                        rotate: 0, // 旋转角度 
                        callback(_base64) {
                            me.user_temp_pic = _base64
                        }
                    })

                }
            })
        }
    })
},

debug后发现是

var size = (orientation >= 5 && orientation <= 8) ? methods.newsize(img.height, img.width, $this.options.width, $this.options.height, $this.options.crop)  : methods.newsize(img.width, img.height, $this.options.width, $this.options.height, $this.options.crop);

这个size对象的width和height为空,导致canvas的INVALID_STATE_ERR错误。

由于业务需要,我必须修改原图,将宽度大于1000的图片压缩至1000,而高度随原图比例被计算出来,所以我做了如下更改:

// 223行,添加如下配置:
resize: false, // 重设图片宽度,高度自动按照比例缩放

// 269行
var ratio = img.width / img.height
if ($this.options.resize && typeof $this.options.resize === 'number') {
    $this.options.width = $this.options.resize
    $this.options.height = $this.options.width / ratio
}

// 然后调用时
canvasResize(_file, {
    resize: 1000, // 新增resize项
    crop: false, // 是否裁剪
    quality: 0.9, // 压缩质量  0 - 1
    rotate: 0, // 旋转角度 
    callback(_base64) {
        me.user_temp_pic = _base64
    }
})

我不是很明白crop项的作用。所以自行增加了一个配置。
如果作者有更好的方法,麻烦解答一下,谢谢~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions