var img = new Image, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), src = ""; // insert image url here img.crossOrigin = "Anonymous"; img.onload = function() { canvas.width = img.width; canvas.height = img.height; ctx.drawImage( img, 0, 0 ); localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") ); } img.src = src; // make sure the load event fires for cached images too if ( img.complete || img.complete === undefined ) { img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; img.src = src; }
上述配置完成后,重启服务器,CORS启用。
然后我们再刷新页面,查询请求头的参数,可以发现多出一个:Access-Control-Allow-Origin:*
,到此证明服务器配置已经生效。同时我们的canvas绘图也可以正常使用了。
刷新页面返回请求响应结果后,HTTP Request Headers的内容:
Remote Address:222.132.18.xx:80
Request URL:
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:js.xx.com
Origin:
Pragma:no-cache
RA-Sid:7CCAD53E-20140704-054839-03c57a-85faf2
RA-Ver:2.8.8
Referer:?uuid=46124642&fid=2&sign=xxx
User-Agent:Mozilla/5.0 (Windows NT 6.1;WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115Safari/537.36
Response Headersview source
Accept-Ranges:bytes
Access-Control-Allow-Origin:*
Connection:close
Content-Length:4010
Content-Type:image/jpeg
Date:Thu, 12 Mar 2015 02:29:43 GMT
ETag:"54f7d1b4-faa"
Last-Modified:Thu, 05 Mar 2015 03:47:00 GMT
Powered-By-ChinaCache:MISS fromCNC-WF-3-3X6
Powered-By-ChinaCache:MISS fromCNC-WF-3-3X5
Server:Tengine
Switch:FSCS附图:
参考文章:
CORS enabled image https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
CORS on Nginx
Nginx CORS实现JS跨域
转载请注明出处,文章来自于freshlover的CSDN空间《Ajax跨域、Json跨域、Socket跨域和Canvas跨域等同源策略限制的解决方法》