fabric 关于背景图跨域问题

696 阅读1分钟

问题

fabric.js里setBackgroundImage使用跨域图片在canvas导出toDataURL()导致报错,把图片转换成base64可解决此问题

DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

解决办法

mounted() {
    this.getURLBase64(this.bgImage).then(res => {
        this.imageUrl = res
        this.setBackgroundImage()
    })
},
methods: {
    // 将远程图片下载本地成为base64图片
    getURLBase64(url) {
        let _this = this;
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest()
            xhr.open('get', url, true)
            xhr.responseType = 'blob'
            xhr.onload = function() {
                if (this.status === 200) {
                    var blob = this.response
                    var fileReader = new FileReader()
                    fileReader.onloadend = function(e) {
                        var result = e.target.result;
                        //console.log(result)
                        //_this.imageUrl = result;
                        resolve(result)
                    };
                    fileReader.readAsDataURL(blob)
                }
            };
            xhr.onerror = function() {
                reject()
            };
            xhr.send()
        })
    },
    
    
    // 设置/修改画布背景图
    setBackgroundImage() {
        this.zoomCanvas.setBackgroundImage(
            this.imageUrl,
            this.zoomCanvas.renderAll.bind(this.zoomCanvas),
            {
                // Needed to position backgroundImage at 0/0
                originX: 'left',
                originY: 'top',
                // Needed to position backgroundImage at 0/0
                left: 0,
                top: 0,
                // Needed to scale backgroundImage
                scaleX: this.zoomCanvas.width / this.initialCanvas.width,
                scaleY: this.zoomCanvas.height / this.initialCanvas.height,
            }
        )
    },
}