Home > Article > Web Front-end > Why Does canvas.toDataURL() Throw a Security Exception When Loading Images From Different Servers?
Cross-Origin Problem in Canvas toDataURL()
Despite ensuring sufficient rest, users may encounter security exceptions when using canvas.toDataURL(). Consider the following code:
<code class="javascript">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) // Security exception occurs here: window.open(frame.toDataURL("image/png")); }</code>
This code attempts to open an image from a different server as base64 data in a new window, but it raises a SECURITY_ERR exception.
According to the specifications, the toDataURL() method of a canvas element throws a SECURITY_ERR exception if its origin-clean flag is set to false. When an image is loaded from a different server, the canvas is tainted and its origin-clean flag is set to false.
Therefore, it's not possible to directly use toDataURL() to obtain base64 data for images sourced from different servers. Alternative techniques, such as CORS or proxies, may be necessary to handle cross-origin images.
The above is the detailed content of Why Does canvas.toDataURL() Throw a Security Exception When Loading Images From Different Servers?. For more information, please follow other related articles on the PHP Chinese website!