【React】canvas设置在线图片时,提示画布被污染,设置crossOrigin就跨域

本地图片没问题,在线图片就会提示画布被污染,看他们说的设置crossOrigin就会提示图片跨域,有解决过的指点下吗
【React】canvas设置在线图片时,提示画布被污染,设置crossOrigin就跨域
直接访问这个图片都可以哒
【React】canvas设置在线图片时,提示画布被污染,设置crossOrigin就跨域

canvas = this.mycanvas;

ctx = canvas.getContext("2d");

const img = new Image();

img.src = backgroundImg;

img.onload = function () {

//...

}

//插入一张在线图片可以显示

//但是调用canvas.toDataURL("image/png");时会报错:

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

canvas = this.mycanvas;

ctx = canvas.getContext("2d");

const img = new Image();

//img.crossOrigin = '';

// img.crossOrigin = "Anonymous"

// img.setAttribute('crossOrigin','anonymous');

img.setAttribute("crossOrigin", 'Anonymous');

img.src = backgroundImg;

// img.src = './sees.png';//本地图片没问题

img.onload = function () {

//...

}

//设置了setAttribute图片就不能显示,出现跨域问题:

//Access to image at 'http://....png' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

回答

img.src = ...那句要最后调用,设置crossOrigin要在前面设置

大概要这样

img.onload = function() {

context.drawImage(this, 40, 40);

};

img.crossOrigin = "Anonymous";

img.src = ...;

参考:https://stackoverflow.com/que...

以上是 【React】canvas设置在线图片时,提示画布被污染,设置crossOrigin就跨域 的全部内容, 来源链接: utcz.com/a/77084.html

回到顶部