canvas跨域加载图片的解决方法

在一次项目中, 需要用canvas绘制图片, 可是canvas绘制图片, 存在跨域问题, 就如下面的两个报错.

  1. execute 'toDataURL'
  2. Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

这里的解决方法是:

var image = new Image();
                            // image.crossOrigin = '';
                            image.setAttribute("crossOrigin",'anonymous')    // 添加改代码, 防止跨域
                            image.onload = function () {
                                var dx = (item.dx - item.width / 2) ? (item.dx - item.width / 2) : 0;
                                var dy = (item.dy - item.height / 2) ? (item.dy - item.height / 2) : 0;
                                _crateCtx.drawImage(image, 0, 0, this.width, this.height, _that.getRule(dx), _that.getRule(dy) + _that.PY, _that.getRule(this.width), _that.getRule(this.height));
                                stepLoad(productList[count], callback && callback)
                                count++;
                            }
                            image.onerror = function () {
                                count++;
                                stepLoad(productList[count], callback && callback)
                            }
                            image.src =  item.src + '?v=3' ;   //添加后缀, 防止缓存;

解决步骤

  1. 添加代码
 image.setAttribute("crossOrigin",'anonymous')    // 添加改代码, 防止跨域
  image.src =  item.src + '?v=3' ;   //添加后缀, 防止缓存;
  1. cnd源站添加header头
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods Get, Post, Options;
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容