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

2018-09-28  本文已影响0人  Biao_349d

在一次项目中, 需要用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;
上一篇下一篇

猜你喜欢

热点阅读