头闻号

深圳市亿宇塑胶五金电子有限公司

生活日用橡胶制品|家居用品加工|厨具|餐具|广告促销礼品|家用塑料制品

首页 > 新闻中心 > 科技常识:详解canvas绘图时遇到的跨域问题
科技常识:详解canvas绘图时遇到的跨域问题
发布时间:2023-02-01 10:34:57        浏览次数:1        返回列表

今天小编跟大家讲解下有关详解canvas绘图时遇到的跨域问题 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关详解canvas绘图时遇到的跨域问题 的相关资料,希望小伙伴们看了有所帮助。

当在canvas中绘制一张外链图片时,我们会遇到一个跨域问题。

示例如下:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>crossorigin</title></head><body> <canvas width="600" height="300" id="canvas"></canvas> <img id="image" alt=""> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var image = new Image(); image.onload = function() { ctx.drawImage(image, 0, 0); document.getElementById('image').src = canvas.toDataURL('image/png'); }; image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg'; </script></body>

当在浏览器中打开这个页面时,你会发现这个问题:

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

这是受限于 CORS 策略,会存在跨域问题,虽然可以使用图像,但是绘制到画布上会污染画布,一旦一个画布被污染,就无法提取画布的数据,比如无法使用使用画布toBlob(),toDataURL(),或getImageData()方法;当使用这些方法的时候 会抛出上面的安全错误

这是一个苦恼的问题,但幸运的是img新增了crossorigin属性,这个属性决定了图片获取过程中是否开启CORS功能:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>crossorigin</title></head><body> <canvas width="600" height="300" id="canvas"></canvas> <img id="image" alt=""> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var image = new Image(); image.setAttribute('crossorigin', 'anonymous'); image.onload = function() { ctx.drawImage(image, 0, 0); document.getElementById('image').src = canvas.toDataURL('image/png'); }; image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg'; </script></body>

对比上面两段JS代码,你会发现多了这一行:

image.setAttribute('crossorigin', 'anonymous');

就是这么简单,完美的解决了!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持爱蒂网。

来源:爱蒂网