Tag Archives: canvas

Tainted canvases may not be exported

Tainted canvases may not be exported.

  • scene
  • solution
  • summary

scene

used HTML canvas for drawing, and then tried to convert to base64 format or binary temporary file through canvas Api toDataURL toBlob, but the error was reported. The error message reads

DOMException: Failed to execute ‘toBlob’ on ‘HTMLCanvasElement: Tainted canvases may not be exported.

DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement: Tainted canvases may not be exported.

understand from literal meaning, said the canvas canvas is polluted, not allowed to export. What behavior causes the canvas to be polluted?After modifying the code, it turns out that the above two methods work as long as you don’t draw your drawImage. DrawImage is used here to draw network images.

solution

baidu time happened to see a
solution to canvas cross-domain access
in which the same-origin policy and the same-origin policy of canvas Api were explained. After reading this article, I am inspired by the use of

in this article

context.getImageData(x,y,width,height)

What if

USES this Api to replace canvas’s toBlob toDataURL interface?After trying, the console reported an error

DOMException: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’ : The canvas has had been tainted by cross – origin data.

same-origin policy error
where the code to load the Image is posted

loadImage(url) {
					return new Promise((resolve, reject) => {
						let img = new Image()
						//img.crossOrigin=""
						img.src = url
						img.onload = function() {
							resolve(img)
						}
					})
				}

after I set img.crossOrigin=”” || img.crossOrign=” “*”, context.getimagedata was able to work properly and was useless because of a problem with the same-origin policy. Could toBlob toDataURL also be a problem due to the same origin policy?After testing, toBlob, toDataURL, works fine.

summary

my problem is solved here, but it is worth noting here that I used the image source drawn with the CDN, and set img.crossOrign to allow cross-domain loading of image resources, but if the server itself does not allow cross-domain access, then this img.crossOrign will not solve any problems. Specific solutions are clearly pointed out in solving canvas cross-domain problem. If your server itself doesn’t support cross-domain, try the solution mentioned in the Canvas cross-domain article. Note down the resolution process here for your reference. If you have any problems, please leave a message.

all right, my old buddy. Bye.