Home >Web Front-end >JS Tutorial >Why does `canvas.toDataURL()` throw a `SECURITY_ERR` when drawing images from a different origin?
Consider the following code:
<pre class="brush:php;toolbar:false"> var frame=document.getElementById("viewer"); frame.width=100; frame.height=100; var ctx=frame.getContext("2d"); var img=new Image(); img.src="http://www.ansearch.com/images/interface/item/small/image.png" img.onload=function() { // draw image ctx.drawImage(img, 0, 0) // Here's where the error happens: window.open(frame.toDataURL("image/png")); }
This code attempts to convert a canvas element to a data URL using the 'toDataURL()' method. However, this results in a 'SECURITY_ERR: DOM Exception 18' error.
The reason for this error stems from the security restrictions imposed by the web browsers. According to the HTML Canvas specifications, if the image being drawn onto the canvas is sourced from a different origin (in this case, from 'http://www.ansearch.com'), the browser will prevent the conversion of the canvas to a data URL. This is done to prevent cross-origin data access and potential security vulnerabilities.
Therefore, if you are attempting to generate a data URL from a canvas element that contains an image from a different origin, you will encounter this security exception. To resolve this issue, you need to ensure that the image is served from the same origin as your web application or explore alternative methods of image conversion.
The above is the detailed content of Why does `canvas.toDataURL()` throw a `SECURITY_ERR` when drawing images from a different origin?. For more information, please follow other related articles on the PHP Chinese website!