显示错误如下:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决方案:
1. 设置 crossOrigin
drawing = new Image();
drawing.src = imgSrc; // can also be a remote URL e.g. http://
var canvas = document.getElementById('id');
var ctx = canvas.getContext('2d');
//drawing.crossOrigin = '';
drawing.setAttribute("crossOrigin",'Anonymous');
drawing.onload = function() {
ctx.drawImage(drawing,0,0);
};
如果服务器没有设置:Access-Control-Allow-Origin,基本无效
2. html2canvas
代码 https://github.com/niklasvh/html2canvas
html2canvas(document.getElementById("id"), {scale: 1, logging: false, useCORS: true, allowTaint: false, proxy: '跨域url'}).then(function(canvas){
//do something
});
原理是利用canvas屏幕截图,对于png文件的url会丢失信息。
3. 终极大杀器利用nginx反向代理
参考:
https://www.jianshu.com/p/f9f4a0d1ddd9
4. WebSocket协议跨域