Canvas图片跨域会遇到的问题及解决方法总结


本文摘自PHP中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于Canvas图片跨域会遇到的问题及解决方法总结,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

尽管不通过 CORS 就可以在 Canvas 画布中使用图片,但是这会污染画布。一旦画布被污染,你就无法读取其数据。例如,你不能再使用画布的 toBlob(), toDataURL() 或 getImageData() 方法,调用它们会抛出安全错误。这种机制可以避免未经许可拉取远程网站信息而导致的用户隐私泄露。

HTML 规范中图片有一个 crossorigin 属性,结合合适的 CORS 响应头,就可以实现在画布中使用跨域 <img> 元素的图像。

crossOrigin/CORS同域跨域无 CORS跨域有 CORS
default支持支持渲染,不支持 toDataURL支持渲染,不支持 toDataURL
anonymousN/A同上支持渲染,支持 toDataURL
use-credentialsN/A同上支持渲染,不支持 toDataURL

总结:Canvas 可以正常的渲染跨域图片,但是在跨域图片没有设置跨域响应头或没有设置 crossOrigin = 'anonymous' 的时候,使用 canvas.toDataURl 会抛出如下错误:

Chrome

没有设置 crossOrigin

1

2

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

at Image.img.onload...

跨域

1

Access to Image at 'http://localhost:3001/canvas.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

设置了 crossOrigin=use-credentials

1

Access to Image at 'http://localhost:3002/canvas.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access.

Safari/Firefox

阅读剩余部分

相关阅读 >>

html5 canvas基本绘图之绘制线条

html5/css3 经典案例-无插件拖拽上传图片(一)

畅谈html5 到底是什么?

浅谈html5和html4之间的不同

h5手机端页面缩放

html5 canvas实现绘制一个像素宽的细线

具体介绍html5移动应用开发的12大特性

如何在html5中使用svg

基于html5的web scada报表图文代码详解

实例讲解h5移动开发ajax上传多张base64格式图片到服务器

更多相关阅读请进入《canvas》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...