CanvasContext2D drawImage() Issue: Load Image and CORS Configuration
When painting an image on a canvas before retrieving its dataURL, an issue may arise where the data returned is empty, containing numerous "A" characters. Additionally, the image may not be drawn when the canvas is appended to the document.
Solution: Load Image Event
To resolve this issue, it is crucial to wait until the image has loaded before attempting to paint it on the canvas. Utilize the load event handler of the element:
var img = new Image(); img.onload = function() { var canvas = document.createElement('canvas'); // ... code to draw the image and retrieve dataURL ... }; img.src = "http://somerandomWebsite/picture.png";
CORS Configuration for Pixel Data Access
Another potential cause is a restriction known as "tainting" of the canvas. To overcome this, correct CORS (Cross-Origin Resource Sharing) configuration is essential.
Note: CORS headers are server-controlled. The cross-origin attribute merely indicates the desire to use CORS. It cannot bypass proper server configuration.
Edge Case: Mixed Image Sources
If images are sourced from both your server and CORS-enabled servers, consider using the onerror event handler to handle non-CORS images.
function corsError() { this.crossOrigin = ''; this.src = ''; this.removeEventListener('error', corsError, false); } img.addEventListener('error', corsError, false);
The above is the detailed content of Why is my Canvas drawImage() empty or filled with 'A's, and how can I fix CORS issues when drawing external images?. For more information, please follow other related articles on the PHP Chinese website!