Home > Web Front-end > JS Tutorial > Why is my Canvas drawImage() empty or filled with 'A's, and how can I fix CORS issues when drawing external images?

Why is my Canvas drawImage() empty or filled with 'A's, and how can I fix CORS issues when drawing external images?

Barbara Streisand
Release: 2024-12-16 14:14:10
Original
749 people have browsed it

Why is my Canvas drawImage() empty or filled with

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";
Copy after login

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.

  • Same-origin images: No problem.
  • External images: Ensure the server allows cross-origin access in its headers and set img.crossOrigin to "use-credentials."
  • Anonymous requests: Set img.crossOrigin to "anonymous" if the server allows anonymous access.

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template