CanvasContext2D drawImage() Issue: Image Loading and CORS
When attempting to draw an image on a canvas before acquiring its dataURL, encountering an empty dataURL or blank canvas rendering can be an issue. This can be attributed to a timing problem and Cross-Origin Resource Sharing (CORS) concerns.
To resolve the timing issue, the image must be fully loaded before attempting to draw it on the canvas. Utilize the onload event handler as follows:
// Create a new image var img = new Image(); // Define a function to execute when the image loads img.onload = function () { var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; var context = canvas.getContext('2d'); context.drawImage(img, 0, 0); var dataURL = canvas.toDataURL(); // Now, the dataURL is available for processing doSomething(dataURL); }; // Set the image source img.src = "http://somerandomWebsite/picture.png";
Additionally, to ensure the functionality of context.toDataURL() and context.getImageData() in the canvas context, images must be acquired in a CORS-compliant manner to avoid canvas "tainting."
It's crucial to note that a CORS header is generated by the server. The cross-origin attribute only informs the server that CORS is desired for image data retrieval; it cannot bypass CORS restrictions if the server is not appropriately configured.
In some cases, images may come from different sources, including your server and CORS-compliant servers. In these situations, utilize the onerror event handler, which is triggered when the cross-origin attribute is set to "anonymous" on a server that does not support CORS:
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 CanvasContext2D drawImage() failing, and how can I fix CORS and image loading issues?. For more information, please follow other related articles on the PHP Chinese website!