Quick answer: A 2D canvas becomes tainted the moment you draw an image, video or SVG from another origin that was not loaded with CORS approval. After that, toDataURL, toBlob and getImageData throw a SecurityError, and WebGL refuses the texture upload outright. The fix has two halves: the asset server sends Access-Control-Allow-Origin, and the game requests the asset with img.crossOrigin = "anonymous" set before src.
The game renders correctly, every sprite is on screen, and then the share button, the save-slot thumbnail or the pixel-perfect hit test throws a SecurityError. Nothing is wrong with the drawing code. The browser has decided the canvas contains pixels your page is not allowed to read, and it only tells you when you try to read them. This guide lists every wording of the error in Chrome, Firefox and Safari, shows how to find the one draw call that tainted the canvas, and covers the server header, the crossOrigin setting, the browser cache trap and the loader options in Phaser, PixiJS, Three.js and Construct 3.
- The exact errors
- What tainting is and why browsers do it
- Where games run into it
- Find the draw call that tainted the canvas
- Fix part 1: the server sends the header
- Fix part 2: the game asks for CORS
- The cache trap
- Engine and framework settings
- When you cannot change the server
- How to confirm the fix
- Screenshots in bug reports depend on a clean canvas
- Related guides
- Frequently asked questions
The exact errors
Chrome and Edge name the method that failed. These are the messages from a current Chrome build:
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Uncaught SecurityError: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
Uncaught SecurityError: Failed to execute 'captureStream' on 'HTMLCanvasElement': Canvas is not origin-clean.
Uncaught SecurityError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The image element contains cross-origin data, and may not be loaded.
Uncaught SecurityError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Tainted canvases may not be loaded.
Older Chrome versions print Uncaught DOMException: where newer ones print Uncaught SecurityError:, and the rest of the line is identical. A WebGL 2 context says WebGL2RenderingContext, and texSubImage2D produces the same pair of messages. Firefox and Safari use one short message for all of these calls:
SecurityError: The operation is insecure.
In every browser the thrown value is a DOMException whose name is SecurityError. On a 2D canvas the draw itself succeeds and the frame looks right; the exception comes later, at the first call that reads pixels back. In WebGL the exception comes at the upload, so the texture never appears.
What tainting is and why browsers do it
Every canvas bitmap has a flag the HTML specification calls origin-clean. It starts out true. Drawing an image, a video frame or another canvas whose pixels came from a different origin, without that origin’s permission, sets it to false. From then on the canvas can still be drawn to and displayed, but anything that would hand the pixels to your script throws. Nothing you draw afterwards makes it clean again, so treat a tainted canvas as tainted for good.
The reason is that an image element can display any URL the player’s browser can reach, including images behind the player’s login cookies or on their home network. Showing those pixels to the player is harmless. Letting a page read them back through a canvas would let any website copy them. Permission to read is exactly what CORS expresses, so an image loaded with CORS approval does not taint.
Tainting spreads. A tainted canvas drawn onto a second canvas taints the second one. So does a pattern made with createPattern from an unapproved image, and so does an ImageBitmap created from one. WebGL is stricter: shaders could leak pixel values through timing, so texImage2D rejects an unapproved image, video or tainted canvas as a texture source. A side effect worth knowing: a WebGL canvas can never be tainted, so if toDataURL on a WebGL canvas returns a blank image without throwing, that is a different problem (the drawing buffer was cleared), covered in the Three.js screenshot guide.
Where games run into it
- Sprite sheets or textures on a CDN or asset subdomain, plus anything that reads the canvas.
assets.mygame.exampleis a different origin frommygame.example, and so is another port orhttpversushttps. The usual readers are a screenshot for a share button, a bug report or a save-slot thumbnail. - Pixel-perfect collision and hit masks. Building an alpha mask, colour-picking an object under the cursor or palette-swapping a sprite all call
getImageDataon an offscreen canvas holding the sprite. - Opening
index.htmlfromfile://. Chrome gives a local page the opaque originnulland treats every local file as cross-origin, so the first local image drawn taints the canvas. Run a local web server. - Player avatars and other remote pictures. Profile images from a social or storefront host, or user-made level thumbnails stored on another domain, are fetched from a server you do not control.
- Video textures. A cutscene or background video served from a video host taints a 2D canvas and is refused by WebGL in the same way as an image.
- SVG images containing
foreignObject. In Chrome, an SVG with aforeignObjectelement taints the canvas when it is loaded from ablob:URL and does not when the same markup is loaded from adata:URL. Safari has historically tainted for any such SVG. If you rasterise HTML text this way, encode the SVG as a data URL and test on Safari.
Things that do not taint: same-origin images, data: URL images, blob: URLs created from bytes your script was allowed to read, and web fonts. Fonts are always fetched with CORS, so a font that loaded at all is safe to draw with fillText.
Find the draw call that tainted the canvas
The exception points at the read, not at the draw that caused it, and there is no property that exposes the flag. During debugging, wrap drawImage and test the canvas after every call. Paste this before the game starts:
(function () {
var proto = CanvasRenderingContext2D.prototype;
var realDraw = proto.drawImage;
var known = new WeakSet();
function isTainted(ctx) {
try { ctx.getImageData(0, 0, 1, 1); return false; }
catch (e) { return e.name === "SecurityError"; }
}
proto.drawImage = function (source) {
var result = realDraw.apply(this, arguments);
if (!known.has(this.canvas) && isTainted(this)) {
known.add(this.canvas);
console.error("Canvas tainted by", source.currentSrc || source.src || source, this.canvas);
console.trace();
}
return result;
};
})();
The first logged source is your culprit, and the trace shows which system drew it. Remove the wrapper afterwards: getImageData on every draw is slow. If nothing is logged and the canvas is still tainted, look for createPattern with a remote image.
For WebGL the stack trace already stops at the failing texImage2D, usually inside the renderer. Turn on Pause on uncaught exceptions in the Sources panel and inspect the image argument to read its src.
Then open the Network tab and click the asset. Two things matter: whether the request carries an Origin header (if not, the game did not ask for CORS), and whether the response carries Access-Control-Allow-Origin (if not, the server did not grant it).
Fix part 1: the server sends the header
The host that serves the images must answer with one of these:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: https://mygame.example
Vary: Origin
The wildcard is fine for public game art. If you echo a specific origin, Vary: Origin is required so that caches keep separate copies per origin. Check what the server really sends, with an Origin header on the request, because many storage hosts only add CORS headers when they see one:
curl -sI -H "Origin: https://mygame.example" https://cdn.example.com/sprites/hero.png
Bucket and CDN configuration for the common hosts is in the guide to game assets blocked by CORS on a CDN.
Fix part 2: the game asks for CORS
The header alone changes nothing. An image element makes a plain request by default, and a plain request taints even when the response happens to include the header. Set crossOrigin before src:
const img = new Image();
img.crossOrigin = "anonymous"; // must come before src
img.onload = () => ctx.drawImage(img, 0, 0);
img.onerror = () => console.error("Image failed (CORS or network):", img.src);
img.src = "https://cdn.example.com/sprites/hero.png";
In markup the attribute is crossorigin="anonymous", and it works the same on video elements. Use anonymous unless the asset really needs cookies; use-credentials also requires a non-wildcard origin and Access-Control-Allow-Credentials: true.
| Game sets crossOrigin | Server sends the header | What happens |
|---|---|---|
| No | No or yes | Image loads and displays, and taints the canvas |
| Yes | No | Image does not load at all: onerror fires |
| Yes | Yes | Image loads and the canvas stays clean |
The middle row surprises people: after adding crossOrigin the sprite disappears and Chrome logs Access to image at '...' from origin '...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. That is progress. The request is now the right kind and the server is the missing half.
The cache trap
You fix both halves and the image still fails, but only on machines that visited before. The browser cached the response from the earlier plain request, which had no CORS header because many hosts only send one when the request has an Origin header. The new CORS request for the same URL is answered from the cache, the cached copy has no header, and the load fails. In a test against a storage-style server in current Chrome, exactly this sequence failed, and it worked again once the server added Vary: Origin.
- Send
Vary: Originon every asset response, with or without anOriginheader on the request. - Request each URL the same way everywhere. A preload
<img>tag or CSS background without CORS, followed by a loader with CORS, recreates the problem. - For players who already hold the bad copy, change the URL: a version query string or a hashed file name.
Engine and framework settings
Phaser 3. The loader fetches images with XMLHttpRequest by default, which is always a CORS request, so a missing header shows up as a failed load (the loaderror event) and not as a tainted canvas. The loader’s crossOrigin value is applied to the image elements it creates and matters most when you switch it to image elements with imageLoadType: "HTMLImageElement" (Phaser 3.60 and later). It is undefined by default:
const config = {
type: Phaser.AUTO,
loader: { crossOrigin: "anonymous" },
scene: { preload, create }
};
function preload() {
this.load.setCORS("anonymous"); // same setting, per scene, before queuing files
this.load.image("hero", "https://cdn.example.com/sprites/hero.png");
}
PixiJS 7 and 8. Assets loads textures with fetch and createImageBitmap by default, so again a missing header is a load failure. If you turn that path off with preferCreateImageBitmap: false, Pixi uses new Image() with its crossOrigin preference, which defaults to "anonymous". Tainting in a Pixi game usually comes from a texture built from your own <img> or <video> element created without the attribute.
Three.js. Every loader has crossOrigin set to "anonymous" by default, and new THREE.TextureLoader().setCrossOrigin("anonymous") sets it explicitly. A texture from a host without the header simply fails to load. The texImage2D error appears when you wrap your own element, for example new THREE.VideoTexture(video) where the video lacks crossOrigin.
Construct 3. Project images ship with the export on the same origin, so the risk is images fetched at runtime, such as the Sprite action that loads an image from a URL. Request those with the anonymous cross-origin option, and make sure the host sends the header, or the System snapshot action will fail on the tainted canvas.
When you cannot change the server
Avatars and other third-party images come from hosts that will not add a header for you. The options, best first:
- Proxy the image through your own origin. A small endpoint on your server fetches the remote image and returns it, either same-origin or with your own CORS header. Restrict it to the hosts you expect so it cannot be used to fetch arbitrary URLs.
- Keep unapproved pixels off the canvas you export. Show avatars as DOM
<img>elements positioned over the game, or draw them on a separate overlay canvas, so the main canvas stays clean for screenshots. - Copy the asset to your own storage at upload time, if your terms allow it.
Fetching the image as a blob and drawing from a blob: URL is not a way round the rule. A normal fetch is a CORS request and rejects when the header is missing. With mode: "no-cors" the request succeeds but the response is opaque: its status reads 0 and response.blob() gives an empty blob, so there are no bytes to turn into an image. A blob URL only helps when CORS already allowed you to read the response.
How to confirm the fix
- Clear the cache or use a private window, load the game from its real URL (not
file://), and trigger every reader: screenshot, thumbnail, hit mask. - Test a profile that visited the old build, to catch the cached-response case.
- Run
document.querySelector("canvas").toDataURL()in the console after a few minutes of play, including screens with remote images. - Repeat in Firefox and Safari, and on the portal build if you publish to one, because the page origin changes there and an allowlist of origins may not include it.
Screenshots in bug reports depend on a clean canvas
A screenshot attached to a bug report is a canvas read like any other. The Bugnet Web SDK captures the game canvas for automatic error reports and for the in-game report form, and when the canvas is tainted the browser refuses that read, so the report arrives without an image. Bugnet cannot work around the rule any more than your share button can. What it does give you is the evidence: an uncaught SecurityError thrown by your own toDataURL or getImageData call is filed once per session with its stack, the last 50 console lines and the user agent, and identical reports from other players stack onto the same entry. That count tells you whether the taint affects one avatar host or every player on the CDN build.
Related guides
- How to Fix Game Assets Blocked by CORS When Served From a CDN
- How to Add In-Game Bug Reporting to a Three.js Game (and Fix Blank Screenshots)
- How to Fix “Failed to execute ‘drawImage’ on ‘CanvasRenderingContext2D’” in Web Games
- What Does “Script error.” Mean in a Web Game? (and How to Get the Real Error)
- How to Fix “TypeError: Failed to fetch” in a Web Game
Frequently asked questions
What does Tainted canvases may not be exported mean?
The canvas contains pixels from an image, video or SVG that came from another origin without CORS approval. The browser still displays the canvas but blocks toDataURL, toBlob and getImageData, because reading those pixels would let a page copy content it has no permission to read.
Why does the canvas still taint after I added Access-Control-Allow-Origin?
The header is only half of the fix. The image must also be requested in CORS mode by setting crossOrigin to anonymous before src. An image loaded without it taints the canvas even when the response includes the header. A cached response from an earlier plain request can also be the cause.
Why did my image stop loading after I set crossOrigin to anonymous?
With crossOrigin set, the browser requires the server to send Access-Control-Allow-Origin. If the header is missing the image fails to load and its error event fires. Add the header on the asset host, and send Vary: Origin so cached copies do not mix.
Can I untaint a canvas?
No. Once a canvas has been tainted, nothing you draw later makes it readable again. Create a new canvas and redraw only content that is same-origin or was loaded with CORS approval, and fix the load that introduced the unapproved pixels.
Does this error happen when I open my game from a file URL?
Yes. Chrome treats a page opened from the file system as an opaque origin and every local file as cross-origin, so the first local image drawn taints the canvas. Serve the game from a local web server while developing.
The header and crossOrigin only work as a pair, and the browser cache remembers the request you made before you had both. Send Vary: Origin and load every asset URL the same way everywhere.