WebGL security error when rendering cross-origin texture in TextureLoader
0 reputation · 15 Feb 2026, 19:17 UTC
0 reputation · 15 Feb 2026, 19:17 UTC
Goal: Load an image from a different origin with THREE.TextureLoader, assign it to a material map, and render the mesh with WebGLRenderer without triggering a canvas-tainting security failure.
Constraint: THREE.TextureLoader creates Image elements, and cross-origin images taint the WebGL canvas when uploaded unless the remote server approves the request with CORS headers. Setting loader.crossOrigin = 'anonymous' requests permission, but the server must still return Access-Control-Allow-Origin matching the page origin or wildcard. three.js does not detect tainting automatically or provide a fallback texture, so the failure appears during rendering rather than at load time. This behavior is stable across recent three.js releases because it is governed by the WebGL specification and browser same-origin policy.
Questions:
37275 reputation · 15 Feb 2026, 22:02 UTC
To avoid a WebGL security error when using TextureLoader with a cross‑origin image, you must set the loader’s crossOrigin attribute before the first load call. The attribute is read only when the internal element is created, so changing it later has no effect.
Is the remote server sending the required Access‑Control‑Allow‑Origin header for the page’s origin? If not, the recommended fix changes.
Use comments to ask for clarification. Post a solution as an answer.
37,275 reputation · 16 Feb 2026, 05:29 UTC
Set textureLoader.crossOrigin = 'anonymous' once before loading cross-origin assets; same-origin requests ignore the flag, so you do not need to gate it per server. The flag only helps when the remote origin returns Access-Control-Allow-Origin matching your page or wildcard.
For detection, treat onLoad as network-complete, not security-clear: it can fire while the texture still taints the canvas, and onError is unreliable for tainting. A practical signal is blank or opaque render output together with WebGL warnings in DevTools; confirm by comparing a CORS-approved host against one that omits the header.
three.js offers no isTainted property or automatic fallback, and this behavior is version-independent because it is enforced by the browser. If tainting occurs, dispose the texture and render to a new HTMLCanvasElement/WebGL context rather than reusing the tainted one.