How to Fix “html2canvas Is Not Defined”
Fix “html2canvas is not defined” by loading the library correctly, importing it in modules, and diagnosing script order, scope, and rendering issues.

“html2canvas is not defined” means the JavaScript name is unavailable in the scope where your code calls it. In an npm or bundler project, install the package and import it in the same module that uses it. In a plain HTML page, load a valid browser build successfully before the script that calls html2canvas. Do not treat cross-origin images, unsupported CSS, or cropped output as the same problem: those occur after the function has loaded.
The official html2canvas setup documents npm install html2canvas, followed by a default import and a call such as html2canvas(element, options). See the html2canvas installation guide.
What the error means
A ReferenceError is raised when JavaScript evaluates an identifier that does not exist in the current scope. MDN describes this as referring to a nonexistent variable and recommends ensuring that a library is loaded before its variables are accessed. MDN: ReferenceError: “x” is not defined.
There are four common reasons:
- The package is not installed in the project that is being built.
- The calling module does not import
html2canvas. - A browser script failed to load, or it loaded after the caller ran.
- The library was imported inside a module, but another script or inline handler expects a global
window.html2canvas.
Choose the fix for your project
| Project type | Correct approach | Typical mistake |
|---|---|---|
| Vite, Webpack, Rollup, Parcel, or another bundler | Install the package and default-import it in the module that calls it. | Installing it elsewhere or assuming an import creates a global. |
| Plain HTML with classic scripts | Load a valid built browser release before the caller. | Wrong URL, failed request, or caller executing first. |
| Native JavaScript module | Use an import in the module and call the imported binding there. | Using the name from an inline handler or unrelated classic script. |

Fix 1: npm and bundler projects
1. Install html2canvas in the correct project
npm install html2canvas
Run this command from the directory containing the application’s package.json. In a monorepo, confirm that the dependency is declared by the workspace that builds the browser code, not only by a sibling package.
2. Import the default export where you call it
import html2canvas from 'html2canvas';
async function captureCard() {
const element = document.querySelector('#card');
if (!element) {
throw new Error('Could not find #card');
}
const canvas = await html2canvas(element);
document.querySelector('#result').replaceChildren(canvas);
}
captureCard().catch(console.error);
The documented call shape is html2canvas(element, options). It returns a Promise that resolves to a canvas. The getting-started examples show the same pattern with document.body.
3. A complete minimal module example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html2canvas module example</title>
</head>
<body>
<article id="card" style="padding:2rem;background:#eef2ff;color:#111827">
<h1>Capture this card</h1>
<p>The module imports html2canvas before calling it.</p>
</article>
<div id="result"></div>
<script type="module" src="/src/app.js"></script>
</body>
</html>
import html2canvas from 'html2canvas';
const source = document.querySelector('#card');
const result = document.querySelector('#result');
if (!source || !result) {
throw new Error('Required elements are missing');
}
html2canvas(source, {
backgroundColor: null,
scale: window.devicePixelRatio
}).then((canvas) => {
result.replaceChildren(canvas);
});
Do not expect the import to create a global
Imports are scoped to the module that declares them. MDN’s modules documentation explains that imported bindings are not automatically placed on window. MDN: JavaScript modules.
This will fail if the inline handler is outside the importing module:
<button onclick="html2canvas(document.body)">Capture</button>
Move the event listener into the module instead:
import html2canvas from 'html2canvas';
document.querySelector('#capture').addEventListener('click', async () => {
const canvas = await html2canvas(document.body);
document.body.append(canvas);
});
Fix 2: plain HTML with script tags
Use a valid built browser release from the project’s current distribution. The html2canvas documentation describes downloading a built release for browser use, but the exact filename and URL can change. Select the current file from the project’s release or distribution instructions rather than copying an unverified path.
Ordered deferred scripts
<script defer src="path/to/html2canvas.browser.js"></script>
<script defer src="app.js"></script>
The important properties are that both files load successfully and that the dependency appears first. MDN documents that deferred scripts execute after parsing in document order. MDN: defer.
Caller script
const target = document.querySelector('#card');
if (!target) {
throw new Error('Missing #card');
}
html2canvas(target)
.then((canvas) => document.body.append(canvas))
.catch((error) => console.error('Capture failed:', error));
Why async often causes this error
Do not mark the dependency and caller as independent async scripts when the caller requires the dependency first. MDN explains that asynchronous scripts execute as soon as they are available, so their order is not guaranteed. MDN: script element.
<!-- Avoid relying on this order -->
<script async src="path/to/html2canvas.browser.js"></script>
<script async src="app.js"></script>
If you must load the library dynamically, start the application only after the load Promise resolves:
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = () => reject(new Error(`Could not load ${src}`));
document.head.append(script);
});
}
await loadScript('path/to/html2canvas.browser.js');
const canvas = await html2canvas(document.body);
Debug the load before changing application code
- Open DevTools and look at the first Console error, not only the final
html2canvaserror. - In Network, reload the page and find the html2canvas request.
- Confirm that the request returns successfully, has the expected JavaScript content type, and is not redirected to an HTML error page.
- Open the loaded script in Sources and check whether an earlier syntax or runtime error stopped execution.
- At the call site, inspect
typeof html2canvas. In a global browser setup it should be"function"; in a module setup, inspect the imported binding instead.
console.log('global binding:', typeof window.html2canvas);
console.log('local binding:', typeof html2canvas);
If the Network request is 404, fix the URL or deployment path. If it is blocked by a content-security policy, update the policy or bundle the package. If the response contains an HTML error document, fix the server route before debugging JavaScript scope.
Common causes and fixes
| Symptom | Cause | Fix |
|---|---|---|
| Error at the first call in bundled code | No import in the module that calls the function, or dependency missing from that workspace. | Install with npm in the correct project and add import html2canvas from 'html2canvas'; to the calling file. |
| Works in one file but not another | The binding is local to a module or function. | Move the call into the importing module or pass a function explicitly; do not assume a module import is global. |
| Plain HTML reports undefined | Dependency request failed or caller ran first. | Inspect Network and use ordered scripts, preferably defer in document order. |
Inline onclick cannot find it |
The library was imported by a module, which does not expose a global. | Attach the event listener from the module that imports html2canvas. |
| Only production fails | Different asset paths, bundler configuration, CSP, or deployment base URL. | Inspect the production HTML and Network requests; verify the built asset is served from the deployed path. |
| Console shows an earlier syntax error | The dependency or caller stopped parsing before creating its binding. | Fix the first syntax/runtime error, reload, then recheck the identifier. |
| Name works but images are missing | Cross-origin image restrictions or inaccessible image resources. | Follow html2canvas’s same-origin and proxy guidance; this is a rendering issue, not a missing-name issue. |
| Name works but CSS differs | html2canvas reconstructs the page from DOM and CSS and does not support every CSS property. | Check the project’s supported features and simplify or adjust unsupported styles. |
| Canvas is blank or cropped | Browser canvas dimension limits or an element larger than the available viewport. | Reduce capture dimensions or configure windowWidth/windowHeight as described in the FAQ. |
Rendering limitations after the error is fixed
html2canvas does not take a native screenshot. It builds a representation from the DOM and the information available to it, so the result can differ from the browser’s exact painted output. html2canvas: About.
Cross-origin images
Images must satisfy the browser’s same-origin rules or be made available through a suitable proxy and CORS configuration. A missing image after a successful call does not mean that html2canvas is undefined.
Unsupported CSS
Some CSS properties and browser effects cannot be reproduced exactly. Compare the output with a simple test element first, then isolate the unsupported style.
Large documents and canvas limits
Very large pages can exceed browser canvas dimensions or memory limits. The project FAQ recommends setting custom windowWidth and windowHeight when an element is cut off. html2canvas FAQ.
Performance and reliability checklist
- Capture the smallest required element instead of the entire document when possible.
- Wait until fonts, images, and dynamic content have finished loading before calling the function.
- Avoid unnecessarily high
scalevalues; output pixels and memory grow with the scale. - Test pages with long lists, sticky elements, animations, web fonts, and lazy images separately.
- Disable animations or capture after a stable state if visual consistency matters.
- Handle the returned Promise with both success and error paths.
- For repeated captures, reuse the page state and avoid creating multiple overlapping captures.
async function captureOnce(element) {
if (!element) throw new Error('Capture target is missing');
await document.fonts?.ready;
const images = [...element.querySelectorAll('img')];
await Promise.all(images.map((img) => {
if (img.complete) return Promise.resolve();
return new Promise((resolve) => {
img.addEventListener('load', resolve, { once: true });
img.addEventListener('error', resolve, { once: true });
});
}));
return html2canvas(element, { scale: Math.min(window.devicePixelRatio, 2) });
}
Or skip the browser setup
If your goal is a reliable website image or PDF rather than rendering a local DOM node, ScreenshotNeo provides a GET API and an MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF. The request below is ready to run; see the ScreenshotNeo API documentation for options.

cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', data);
ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Cost and operational notes
html2canvas runs in the visitor’s browser, so there is no screenshot API request cost, but it consumes the page’s CPU and memory and is constrained by browser security rules. A hosted capture service moves rendering to a remote browser and adds network latency and plan usage. For ScreenshotNeo, cache hits and unsuccessful page verdicts are not billed, while successful clean shots are billed according to the plan. Choose the approach based on whether you need a local DOM capture or a URL-level capture that works without maintaining browser automation.
FAQ
Why is html2canvas undefined only in production?
Production often changes asset paths, CSP rules, bundler output, or script ordering. Inspect the deployed HTML and Network panel for the first failed request.
Can I use window.html2canvas after importing the package?
Not automatically. Module imports are scoped. Use the imported binding in that module instead of relying on a global.
Should I use async or defer?
Use module imports or ordered defer scripts for dependencies. Independent async scripts do not guarantee execution order.
Does fixing the ReferenceError guarantee a pixel-perfect screenshot?
No. html2canvas reconstructs the page from DOM and CSS, and cross-origin images, unsupported styles, and canvas limits can affect the result.
When should I use ScreenshotNeo instead?
Use it when you need a URL capture without setting up a browser library, especially when consent banners, popups, chat widgets, bot checks, or failed pages must be handled consistently.


