How to solve cross-domain issues encountered during Canvas drawing

This article mainly introduces how to solve cross-domain problems encountered during Canvas drawing, have a certain reference value, and friends who need it can be referred to. I hope that everyone has a big gain after reading this article. Let’s take a look at you with everyone.

When drawing an external chain picture in Canvas, we will encounter a cross-domain problem.

  CrossORIGIN       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 = ' IT / U = 34973009994, 2503543630 & fm = 27 & gp = 0.jpg ';    When this page is opened in the browser, you will find this problem:    UNCAUGHT DOMEXCEPTION: FAILED TO EXECUTE'TodataURL' on 'htmlcanvaselement': Tainted Canvas May Not Be Exported.  This is limited to the CORS policy, there is a cross-domain problem, although the image can be used, but draw to the canvas will pollute Canvas, once a canvas are contaminated, it will not be able to extract the data of the canvas, such as the use of the canvas TOBLOB (), TodataURL (), or getImageData () method; when using these methods, the above security error is thrown   This is a distracted problem, but fortunate is IMG to increase the crossorigin property. This property determines whether the image is enabled during the image. CORS function: 


VAR canvas = document.getlementByid (‘canvas’); var CTX = Canvas. GetContext (‘2D’); var image = new image (); image.setttribute (‘Crossorigin’, ‘Anonymous’); Image.onLoad = function () {CTX.drawImage (image, 0, 0); Document.GetElementByid (‘image’). src = canvas.todataURL (‘image / png’);}; image.src = ‘, 2503543630&fm=27&gp=0.jpg ‘;

Contrast two sections of JS code, You will find more this line:
 Image.setttribute ('Crossorigin', 'Anonymous');     is as simple, perfect Solved!   Thank you for reading this article carefully, I hope that Xiaobian sharing how to solve the cross-domain problem of Canvas drawing helps everyone, and I hope everyone will support Tumi clouds. Pay attention to Tumi Cloud Industry Information Channel, find TUMI clouds, detailed solutions waiting for you!                      
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment