在一次项目中, 需要用canvas绘制图片, 可是canvas绘制图片, 存在跨域问题, 就如下面的两个报错.
- execute 'toDataURL'
- 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' ; //添加后缀, 防止缓存;
解决步骤
- 添加代码
image.setAttribute("crossOrigin",'anonymous') // 添加改代码, 防止跨域
image.src = item.src + '?v=3' ; //添加后缀, 防止缓存;
- 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;
网友评论