一个前端操作canvas出现跨域问题的解决方案
-

出现现象:
前端项目中需要使用canvas对网络图片进行操作,
当使用到toDataUrl等操作就会报错:

SecurityError: the operation is insecure
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

这个时候可能你会和我一样使劲百度谷歌找到一堆这样的回答:

  1. 设置了crossOrigin = 'anonymous
  2. image.setAttribute('crossOrigin', 'anonymous');
  3. 把图片转成base64,用canvas的方法(这不是死循环?)

最后使用了以下方法实现:


getBase64 = (imageUrl:string)=>{
    fetch(imageUrl)
        .then((response)=>{
            response.blob()
            .then((blob)=>{
                let oFileReader = new FileReader();
                oFileReader.onloadend = (e:any)=>{
                    let base64 = e.target.result;
                     //项目用的是react,这里的this.canvasImage是定义在组件内的
                    this.canvasImage.src = base64;
                };
                oFileReader.readAsDataURL(blob);
            })
    })
};

然后在使用方法就很明显了:

async componentDidMount(){
    if (this.canvas.current){
        let canvas = this.canvas.current;
        canvas.width = this.imageWidth;
        canvas.height = this.imageHeight;
        this.context = canvas.getContext('2d');
        this.canvasImage.src = await this.getBase64('这里是图片的网址');
        this.canvasImage.onload = ()=>{
            this.context.drawImage(this.canvasImage,0,0,this.imageWidth,this.imageHeight);
            let context = this.context;
            . . .
        }
    }
}

参考:https://www.cnblogs.com/lxk0301/p/11569044.html

最后修改:2020 年 04 月 24 日 06 : 02 PM
如果覺得我的文章對你有用,請隨意讚賞