"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does canvas.toDataURL() Throw a Security Exception When Loading Images From Different Servers?

Why Does canvas.toDataURL() Throw a Security Exception When Loading Images From Different Servers?

Published on 2024-11-11
Browse:645

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:

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"));
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3