How to Fix html2canvas Rendering for Data URIs
Fix blank html2canvas exports caused by CORS, redirects, SVG data URIs, CSP, and timing with a practical diagnostic and repair guide.

Direct answer: html2canvas does not take a native browser screenshot. It rebuilds a scene from the DOM, then draws images and styles into a canvas. A data URI can render blank when it is malformed, has no usable SVG dimensions, is blocked by Content Security Policy, contains nested external resources, or when another image taints the canvas through a cross-origin response without CORS approval. Start by classifying the failing URI, inspect the final network response after redirects, wait for images to decode, and keep the canvas exportable with allowTaint: false. Use useCORS: true only when the final image response sends the required CORS header. If you cannot control that server, host the asset on your origin or use a trusted proxy.
This guide covers PNG, JPEG, WebP, SVG, CSS background data URIs, redirects, Safari-specific SVG problems, CSP, timing, proxies, diagnostics, and production reliability.
1. Understand what html2canvas is rendering
html2canvas reconstructs a DOM scene. It is not equivalent to the browser’s screenshot command, so unsupported CSS, filters, fonts, blend modes, and browser-specific behavior can differ from the live page. The project’s FAQ states that it cannot circumvent browser content-policy restrictions, and that drawing an image from another origin without CORS approval taints the canvas. A tainted canvas cannot be read with toDataURL() or toBlob().html2canvas FAQ
A data URI is still an image resource. It avoids an HTTP request for the outer image, but it does not bypass parsing, SVG security rules, CSP, or failures in resources nested inside the SVG. Also inspect every other image and CSS background in the capture: one non-CORS image can make the final canvas unreadable.
2. Classify the failing URI first
Inspect the exact src or background-image value in DevTools. Put it into one of these categories:

| URI type | What to inspect | Typical repair |
|---|---|---|
data:image/png;base64,... |
Base64 validity, MIME type, complete padding, image dimensions | Decode it independently, then wait for img.decode() |
data:image/svg+xml,... |
Encoding, quoting, XML validity, width, height, and viewBox |
Percent-encode or base64-encode consistently and provide intrinsic dimensions |
| Normal HTTP(S) URL | Final URL after redirects and its Access-Control-Allow-Origin header |
Enable CORS on the final server, use the final CDN URL, or proxy it |
SVG containing <image> or an external stylesheet |
Every nested resource and its origin | Inline or same-origin all dependencies, or proxy them |
CSS background-image |
URL quoting, escaped characters, and CSS parser termination | Quote the URL and escape characters that close the CSS value |
3. Check the actual fetched resource and CORS
For a network image, open the Network panel, reload, and follow redirects. The browser evaluates CORS on the final response. A URL that appears same-origin can redirect to a CDN or image host whose response does not include Access-Control-Allow-Origin. The html2canvas configuration documents allowTaint: false, useCORS: false, proxy: null, and imageTimeout: 15000 as defaults.Configuration
MDN describes the browser rule precisely: once data loaded from another origin is drawn without CORS approval, the canvas becomes tainted. useCORS: true asks html2canvas to request images with CORS, but it cannot add permission to a response that does not provide it.MDN: CORS enabled image
- Open the image request in DevTools.
- Record the final URL after every redirect.
- Check the response for
Access-Control-Allow-Origin. It must allow the page origin, or use*where that is appropriate for a non-credentialed request. - Check whether cookies or authorization are required. Wildcard CORS cannot be combined with credentialed requests.
- Test the final URL directly in a minimal page on the same origin as your application.
4. Use the correct html2canvas options
const canvas = await html2canvas(document.querySelector('#capture'), {
allowTaint: false,
useCORS: true,
proxy: null,
imageTimeout: 15000,
logging: true,
onclone: clonedDocument => {
// Make controlled changes in the cloned document if needed.
},
onError: error => console.error('html2canvas resource error', error)
});
const png = canvas.toDataURL('image/png');
Use useCORS: true only if the final response is CORS-enabled. If the image server cannot send the header, remove that option and choose same-origin hosting or a proxy. Setting allowTaint: true may let drawing continue, but it sacrifices exportability; toDataURL() can still fail. Keep it false whenever the result must be downloaded or uploaded.
Useful options include:
| Option | Use it when | Important limit |
|---|---|---|
allowTaint |
You accept a canvas that may not be readable | Does not grant CORS permission |
useCORS |
The image server sends the required CORS header | Redirects can defeat the request strategy |
proxy |
The remote server cannot be changed | The proxy must fetch and return an image safely and with suitable headers |
imageTimeout |
Images load slowly or a page contains many assets | A longer timeout increases waiting time; it does not fix CORS |
logging |
You need resource and parsing diagnostics | Disable noisy logging in production |
onclone |
You need to alter the cloned DOM without changing the live page | Changes affect only the capture clone |
scale, width, height |
You need predictable output dimensions | Large values increase memory and render time |
5. Wait for images before capturing
An image element can be marked complete while decoding has failed or while a dependent resource is still unavailable. Wait for load or decode before invoking html2canvas:
const node = document.querySelector('#capture');
await Promise.all([...node.querySelectorAll('img')].map(img =>
img.complete
? img.decode?.().catch(() => {})
: new Promise(resolve => {
img.onload = resolve;
img.onerror = resolve;
})
));
const canvas = await html2canvas(node, {
allowTaint: false,
useCORS: true,
imageTimeout: 15000,
logging: true,
onError: err => console.error('html2canvas resource error', err)
});
const png = canvas.toDataURL('image/png');
Use the useCORS line only when the final image response is CORS-enabled. Otherwise remove it and use same-origin hosting or proxy. Waiting solves races and incomplete decoding; it does not override browser security.
6. Repair SVG data URIs
SVG data URIs have additional failure modes. Choose one encoding method and apply it consistently. For a non-base64 URI, percent-encode characters that have meaning in a URL, CSS declaration, or HTML attribute. Quote the URL in CSS. For base64, ensure the payload is complete and the MIME type is image/svg+xml.

const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='240' height='80' viewBox='0 0 240 80'>
<rect width='240' height='80' fill='%23f2f2f2'/>
<circle cx='40' cy='40' r='24' fill='%233b82f6'/>
</svg>`;
const image = document.createElement('img');
image.width = 240;
image.height = 80;
image.src = `data:image/svg+xml,${encodeURIComponent(svg)}`;
document.querySelector('#capture').append(image);
await image.decode();
Give the SVG usable intrinsic dimensions with width, height, and a matching viewBox. A reported html2canvas issue shows that a zero-height SVG can cause createPattern failure. Another project pull request discusses escaped non-base64 SVG data URIs in CSS and Safari tainting; treat those records as conditions to test, not as a guarantee that every browser or release behaves identically.
Inline the SVG’s nested resources whenever possible. An <image href='https://...'>, external stylesheet, web font, or filter can introduce another origin and another CORS requirement. Replace nested URLs with data URIs, serve them from your origin, or proxy them. Check your browser’s console for XML parse errors and blocked-resource messages.
7. Check Content Security Policy and browser timing
A restrictive CSP can block data: or blob: images even though the URI itself is valid. Inspect the console for a CSP violation and add only the schemes and hosts your application actually needs to img-src. For example, a policy may need img-src 'self' data: blob: https://cdn.example; your policy must match your deployment and security requirements.
Call img.decode() after assigning src, wait for fonts when text metrics matter, and avoid capturing while layout is changing. Use logging, imageTimeout, and onError to identify failures instead of treating a blank canvas as a rendering mystery.
8. Handle redirects and proxies
A same-origin image URL can redirect to a CDN before the browser fetches the bytes. A documented project issue reports that useCORS was not applied early enough for this pattern. Prefer the stable final CDN URL, configure CORS on that CDN, or proxy the request through a server you control. Do not assume that changing the visible URL or adding useCORS fixes a redirect.
A proxy should accept an allowlisted URL, fetch it with strict timeouts, validate the content type and size, and return the bytes with predictable headers. Avoid an open proxy: it can be abused to fetch internal services. If privacy or latency rules make a proxy unsuitable, copy the asset to same-origin storage instead.
9. Minimal reproduction and diagnostic workflow
- Create a page containing one same-origin PNG data URI.
- Capture it with
allowTaint: falseand export withtoDataURL(). - Replace the PNG with the failing SVG or CSS background.
- Add nested SVG resources one at a time.
- Add external images and inspect each final response for CORS.
- Test Chromium and Safari separately if SVGs or CSS backgrounds are involved.
- Only after the minimal case works, reintroduce transforms, filters, fonts, lazy content, and the rest of the application.
10. Troubleshooting common errors
| Symptom or error | Cause | Fix |
|---|---|---|
| Blank image for a PNG data URI | Malformed base64, wrong MIME type, decode race, or CSP block | Validate the payload, wait for decode(), inspect console CSP errors |
| Blank inline SVG | Unescaped characters, invalid XML, or missing dimensions | Use consistent encoding, quote the URI, add width, height, and viewBox |
useCORS: true changes nothing |
Final response lacks Access-Control-Allow-Origin, or a redirect reaches a CDN |
Fix final-server CORS, use the final URL, or proxy it |
SecurityError: Tainted canvases may not be exported |
An image was drawn without CORS approval | Keep allowTaint: false; make every image same-origin or CORS-enabled |
createPattern or zero-size errors |
SVG has zero or missing intrinsic dimensions | Set dimensions and a valid viewBox |
| Works locally but fails in production | Different origin, CSP, CDN redirect, cookies, or headers | Compare final requests and response headers in both environments |
| Intermittent missing images | Capture starts before decode, lazy loading, or image timeout | Trigger lazy loading, await decode, and tune imageTimeout |
| Safari only fails | SVG data-URI escaping, nested resources, or browser-specific security behavior | Use conservative percent encoding or base64, inline dependencies, and test a minimal Safari case |
11. Performance, reliability, and cost considerations
Large DOM trees, full-page captures, high scale, enormous SVGs, and many decoded images consume substantial memory. Capture the smallest element that meets your requirement, resize source assets, avoid unnecessary shadows and filters, and release canvases after converting them to a Blob. A lower scale reduces memory; a higher scale improves pixel density but can cause slow captures or browser crashes.
For repeatable exports, freeze the page state, wait for fonts and images, use deterministic data, and record the browser, viewport, device-pixel ratio, and URL. Set a finite image timeout and surface errors to monitoring. Cache stable data URIs or same-origin assets, but invalidate the cache when content changes. A proxy adds a network hop and operational dependency, so measure its latency and enforce request limits.
html2canvas itself is a client-side library; its cost is the browser CPU, memory, bandwidth, and any proxy infrastructure you operate. Browser security is the limiting factor, not a missing html2canvas switch.
12. Or skip the browser setup
If you need a clean screenshot or PDF from a URL rather than a DOM canvas, ScreenshotNeo provides a website screenshot API and MCP server. It accepts one GET request and returns PNG, JPEG, WebP, or PDF. The service accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled.
Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. There is a free allowance of 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan. See the ScreenshotNeo API documentation for all options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get('https://api.screenshotneo.com/v1/shot', params={'access_key': 'YOUR_API_KEY', 'url': 'https://stripe.com'}, timeout=90)
open('shot.webp', 'wb').write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Use ScreenshotNeo when you want the browser setup, CORS debugging, consent cleanup, and capture infrastructure handled for you. Create a free ScreenshotNeo account with 1,000 screenshots each month and no card.
13. Practical checklist
- Classify the URI as PNG, JPEG, WebP, SVG, CSS background, or nested SVG resource.
- Validate data-URI encoding and MIME type.
- Add SVG dimensions and a usable viewBox.
- Wait for image decoding and lazy-loaded content.
- Inspect redirects and the final response’s CORS header.
- Keep
allowTaint: falsewhen exporting. - Use
useCORS: trueonly with a CORS-enabled final response. - Use same-origin hosting or a controlled proxy when you cannot change the image server.
- Check CSP for
data:,blob:, and required hosts. - Reduce to one image in a minimal reproduction before adding complexity.
14. FAQ
Does a data URI eliminate CORS?
It eliminates the outer HTTP request, but it does not make nested SVG resources same-origin, bypass CSP, or protect the canvas from other cross-origin images in the capture.
Should I set allowTaint: true?
Only when you do not need to read or export the canvas. For PNG or JPEG output, keep it false and repair the offending resource.
Can html2canvas reproduce every CSS effect?
No. It reconstructs supported DOM and CSS features, so the result can differ from a native browser screenshot.
Why does the same URL work in an <img> but fail in html2canvas?
Displaying an image does not require the canvas to be readable. Exporting requires CORS approval for every drawn cross-origin resource.
When is a server screenshot API a better fit?
Use one when you need URL-level captures, PDFs, scheduled jobs, consistent browser execution, consent cleanup, or a result that does not depend on the page’s CORS and CSP configuration.


