How to Use html2canvas with Vue.js
Capture Vue-rendered elements with html2canvas using refs, async rendering, CORS-safe images, export options, troubleshooting, and a server alternative.

Direct answer: add a Vue template ref to the element you want to capture, wait until the component is mounted, pass that DOM element to html2canvas, and await the returned Promise. The Promise resolves to a canvas that you can display, download, or convert to a data URL. This is a browser-side reconstruction of the DOM, not a native pixel screenshot, so cross-origin images and unsupported CSS need special handling.
Install html2canvas with the command in the official getting-started guide:
npm install html2canvas
1. Vue 3.5+: capture a template ref
Vue 3.5 and newer provide useTemplateRef(). The ref is populated after mount and can become null if the element is removed by v-if, so always guard it.
<script setup>
import { useTemplateRef, ref } from 'vue'
import html2canvas from 'html2canvas'
const captureTarget = useTemplateRef('capture-target')
const previewUrl = ref('')
const errorMessage = ref('')
async function capture() {
const element = captureTarget.value
if (!element) return
errorMessage.value = ''
try {
const canvas = await html2canvas(element, {
backgroundColor: null,
useCORS: true,
scale: window.devicePixelRatio,
})
previewUrl.value = canvas.toDataURL('image/png')
} catch (error) {
errorMessage.value = error instanceof Error ? error.message : String(error)
}
}
function download() {
if (!previewUrl.value) return
const link = document.createElement('a')
link.download = 'vue-capture.png'
link.href = previewUrl.value
link.click()
}
</script>
<template>
<section ref='capture-target' class='card'>
<h1>A Vue-rendered card</h1>
<p>This whole section is the capture target.</p>
</section>
<button type='button' @click='capture'>Capture</button>
<button type='button' :disabled='!previewUrl' @click='download'>Download PNG</button>
<p v-if='errorMessage' role='alert'>{{ errorMessage }}</p>
<img v-if='previewUrl' :src='previewUrl' alt='Captured card preview' />
</template>
Calling capture() from a button means the element exists and the user has reached the rendered state. If the component renders data asynchronously, call it only after that data and its images are ready.
2. Vue before 3.5: use ref(null)
Before Vue 3.5, declare a matching ref yourself. The template ref name must match the variable used in the template.
<script setup>
import { ref } from 'vue'
import html2canvas from 'html2canvas'
const captureTarget = ref(null)
async function capture() {
if (!captureTarget.value) return
const canvas = await html2canvas(captureTarget.value, {
useCORS: true,
backgroundColor: '#ffffff',
})
document.querySelector('#preview').src = canvas.toDataURL('image/png')
}
</script>
<template>
<div ref='captureTarget'>Capture this Vue content</div>
<button type='button' @click='capture'>Capture</button>
<img id='preview' alt='Capture preview' />
</template>
3. Options API example
With the Options API, access the ref through this.$refs in a method. It is available after mounted(), never during the initial render.
<script>
import html2canvas from 'html2canvas'
export default {
data() { return { previewUrl: '' } },
methods: {
async capture() {
const element = this.$refs.captureTarget
if (!element) return
const canvas = await html2canvas(element, { useCORS: true })
this.previewUrl = canvas.toDataURL('image/png')
},
},
}
</script>
<template>
<article ref='captureTarget'>Vue content</article>
<button type='button' @click='capture'>Capture</button>
<img v-if='previewUrl' :src='previewUrl' alt='Captured content' />
</template>
4. Wait for Vue, fonts and images
A mounted component can still be visually incomplete. Use nextTick() after state changes, wait for image decoding, and then capture.
<script setup>
import { nextTick, useTemplateRef } from 'vue'
import html2canvas from 'html2canvas'
const target = useTemplateRef('target')
function waitForImages(root) {
return Promise.all(Array.from(root.querySelectorAll('img')).map((img) => {
if (img.complete) return img.decode?.().catch(() => {})
return new Promise((resolve) => {
img.addEventListener('load', resolve, { once: true })
img.addEventListener('error', resolve, { once: true })
})
}))
}
async function captureAfterUpdate() {
await nextTick()
if (!target.value) return
await document.fonts?.ready
await waitForImages(target.value)
return html2canvas(target.value, { useCORS: true })
}
</script>
<template>
<div ref='target'>Content that depends on reactive data</div>
</template>
5. Export formats and element scope
html2canvas(element, options?) accepts the actual element, not a selector string. To capture one child, put a ref on that child. To capture a full page, use the page root, but keep the canvas size within browser limits.
const canvas = await html2canvas(element, {
width: element.scrollWidth,
height: element.scrollHeight,
windowWidth: element.scrollWidth,
windowHeight: element.scrollHeight,
scrollX: 0,
scrollY: 0,
})
const png = canvas.toDataURL('image/png')
const jpeg = canvas.toDataURL('image/jpeg', 0.92)
const webp = canvas.toDataURL('image/webp', 0.90)
Use backgroundColor: null for transparency, or a color such as #ffffff for an opaque background. scale controls output resolution; its default follows the device pixel ratio. A larger scale increases sharpness and memory use.
6. Useful html2canvas configuration
| Option | Use it for | Practical note |
|---|---|---|
backgroundColor |
Canvas background | null keeps it transparent. |
useCORS |
Images that opt into cross-origin loading | It only works when the image server sends suitable CORS headers. |
proxy |
Routing image requests through a controlled proxy | The proxy must fetch and serve the asset correctly. |
allowTaint |
Allowing cross-origin content to taint the canvas | A tainted canvas cannot be read or exported normally; do not use it to solve downloads. |
scale |
Output density | Higher values produce larger canvases and use more memory. |
width, height |
Explicit capture dimensions | Useful for a fixed crop. |
x, y |
Capture offset | Combine with dimensions for a subsection. |
windowWidth, windowHeight |
Viewport dimensions used while rendering | Set to scroll dimensions for long content when appropriate. |
ignoreElements |
Skip elements programmatically | Return true for controls or other content to omit. |
data-html2canvas-ignore |
Skip marked elements declaratively | Add the attribute to an element you do not want in the output. |
onclone |
Adjust the cloned document | Changes apply to the clone, not the live Vue page. |
imageTimeout |
Limit image loading wait time | Choose a value that matches asset latency. |
logging |
Diagnose rendering problems | Enable while investigating, then disable noisy logs. |
See the html2canvas configuration reference for the complete option list. The library clones the document and draws the styles it implements; it does not read the browser’s final pixels.
7. Hide or change content only in the clone
Use data-html2canvas-ignore for a simple omission, or onclone when the captured version needs different styling.
const canvas = await html2canvas(target.value, {
ignoreElements: (element) => element.matches('.no-capture, button'),
onclone: (clonedDocument) => {
const clonedTarget = clonedDocument.querySelector('.capture-target')
clonedTarget?.classList.add('capture-mode')
},
})
<button class='no-capture' type='button'>Edit</button>
8. Cross-origin images and CORS
Images hosted on another origin are the most common source of missing content or an unreadable canvas. useCORS: true asks the browser to use CORS, but html2canvas cannot override the browser’s content policy. The image server must return suitable CORS headers. If you control neither server, serve the image through a controlled proxy and set proxy.
Do not use allowTaint: true as a download workaround: once a canvas is tainted, calls such as toDataURL() are blocked. Check the browser console and image response headers.
9. CSS fidelity and unsupported features
html2canvas reconstructs the target from DOM and computed styles. It supports only the CSS properties implemented by the project, so the live page and canvas can differ. Test designs that rely on advanced effects, filters, blend modes or complex clipping in every target browser. The about documentation explains this model.
When exact browser pixels matter, use a native browser screenshot mechanism instead of treating html2canvas as a pixel sampler.
10. Large pages, blank output and cropped captures
Canvas limits vary by browser, operating system and device. Very tall or wide pages can produce a blank or partial result, or fail during allocation. Reduce scale, capture smaller elements, set windowWidth and windowHeight to appropriate scroll dimensions, or split long pages into sections.
Also check that the ref is non-null, the element is visible, and the capture is not running while a v-if branch removes the element. A zero-sized or detached node can produce an empty canvas.
11. Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
captureTarget.value is null |
Capture ran before mount or after v-if removed the node. |
Call from a mounted event, await nextTick(), and guard the ref. |
| Images are missing | Cross-origin response lacks CORS headers, or images have not loaded. | Enable useCORS, configure the image server or proxy, and wait for decoding. |
SecurityError: canvas has been tainted |
An image was drawn without permitted CORS. | Fix response headers or proxy the asset; do not rely on allowTaint for export. |
| CSS looks different | The property is not implemented or the clone has different dimensions. | Check supported features, use onclone, and test in the target browser. |
| Canvas is blank or cut off | Dimensions exceed a platform limit, or the target has no layout size. | Capture smaller sections, lower scale, set dimensions explicitly, and confirm visibility. |
| Capture never finishes | Slow or stalled resources, especially images. | Set a suitable imageTimeout, inspect network requests, and remove unnecessary resources. |
| Works in browser but not Node.js | html2canvas depends on browser DOM and canvas APIs. | Run it in a browser; use Puppeteer or Playwright for server-side work. |
12. Performance, reliability and cost
- Capture the smallest element that meets the requirement; full-page clones consume more memory.
- Use the lowest
scalethat meets quality needs, especially on mobile. - Wait for fonts and images once, then reuse the canvas for several exports.
- Disable debug logging in production and omit controls with
ignoreElements. - Expect variation with browser version, device pixel ratio, loaded fonts and available memory.
- html2canvas runs in the user’s browser, so each capture uses client CPU and memory and has no server-side retry model.
13. Or skip the browser setup
If you need a server-generated image or PDF from a URL rather than a Vue DOM node, ScreenshotNeo provides one GET request. It accepts cookie and consent banners like a visitor, then removes 60+ known consent platforms plus newsletter popups and chat widgets; each step can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are free, and responses identify the result with X-Page-Verdict and X-Billed headers. Its MCP server works with Claude, Cursor and other MCP clients.
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}`);
There are 1,000 free screenshots each month with no card. Paid plans start at $5 for 3,000 shots, and every feature is on every plan. Create a free ScreenshotNeo account.
14. FAQ
How do I use html2canvas in Vue?
Put a template ref on the target, wait until it is mounted, then call await html2canvas(ref.value).
Can html2canvas capture a component before it is mounted?
No. The ref is unavailable before mount. Capture after mount or after nextTick().
Why are my images not rendered?
Usually the image origin lacks CORS headers, or the image has not finished loading. Use useCORS, configure a proxy, and wait for images.
Is html2canvas suitable for Node.js?
No. It needs browser APIs. Use Puppeteer or Playwright for server-side browser screenshots.
Does html2canvas produce a native screenshot?
No. It recreates the DOM with supported styles, so fidelity depends on the page and browser.


