Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set the image’s src to a complete Base64 data URL, wait for that replacement image to finish loading, and only then call html2canvas(). jQuery can change the DOM element, but it cannot bypass browser same-origin rules. If the original image is on another domain, obtain its bytes through a CORS-enabled response or an authorized same-origin proxy first.

Working replacement pattern

This example replaces #target-image and captures the element containing it. The dataUrl value must include the media type and the base64, marker, not just the encoded payload.

const dataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...';
const $image = $('#target-image');

$image.one('load error', function (event) {
  if (event.type === 'error') {
    console.error('The replacement image could not be decoded.');
    return;
  }

  html2canvas(document.querySelector('#capture'))
    .then(function (canvas) {
      document.body.appendChild(canvas);
    })
    .catch(function (error) {
      console.error('html2canvas failed:', error);
    });
});

$image.attr('src', dataUrl);

The html2canvas call returns a Promise that resolves to the output canvas. Waiting for the image event prevents a capture from racing the replacement. The error branch makes a failed conversion visible instead of silently capturing a broken image.

Handle cached or already-complete images

A browser can finish loading a data URL immediately, before a listener is attached in more complex code. Check the underlying DOM image after assigning src, and verify naturalWidth:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
const image = document.querySelector('#target-image');
const dataUrl = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...';

function capture() {
  html2canvas(document.querySelector('#capture'))
    .then(canvas => {
      const outputUrl = canvas.toDataURL('image/png');
      document.querySelector('#download-link').href = outputUrl;
    })
    .catch(console.error);
}

image.addEventListener('load', capture, { once: true });
image.addEventListener('error', function () {
  console.error('Invalid or unsupported Base64 image.');
}, { once: true });
image.src = dataUrl;

if (image.complete) {
  if (image.naturalWidth > 0) {
    capture();
  } else {
    console.error('The image completed with a decoding error.');
  }
}

Guard against invoking capture() twice if your surrounding application can fire both the event and the completion check; a boolean flag or a one-shot helper is sufficient.

What a valid Base64 image URL contains

Use this structure:

data:<MIME type>;base64,<Base64 bytes>
  • PNG: data:image/png;base64,...
  • JPEG: data:image/jpeg;base64,...
  • WebP: data:image/webp;base64,...
  • GIF: data:image/gif;base64,...

Do not put a file path, a URL-encoded image URL, or a bare Base64 string in src. The browser needs the MIME type to decode the data. Base64 also increases the byte representation by roughly one third, so very large images consume more HTML and memory than a normal URL.

Converting an image to a data URL

If an image is already same-origin, fetch it as a Blob and use FileReader. This obtains the bytes before jQuery performs the replacement:

function imageUrlToDataUrl(url) {
  return fetch(url)
    .then(function (response) {
      if (!response.ok) {
        throw new Error('Image request failed: ' + response.status);
      }
      return response.blob();
    })
    .then(function (blob) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function () { resolve(reader.result); };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    });
}

imageUrlToDataUrl('/assets/logo.png')
  .then(function (dataUrl) {
    $('#target-image').attr('src', dataUrl);
    // Attach the load/error handling shown earlier before capture.
  })
  .catch(console.error);

For a cross-origin URL, this fetch succeeds only when the server permits your origin with CORS headers. A server response that lacks the required Access-Control-Allow-Origin header cannot be made readable by changing jQuery code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

CORS, same-origin policy and proxy choices

html2canvas reconstructs a canvas from DOM and style information; it is not a pixel-level browser screenshot. A foreign image can taint the canvas, after which reading it with toDataURL() or similar APIs fails. The project’s FAQ, limitations documentation and MDN CORS guidance describe this boundary.

Rank #2
KOOTION USB C Flash Drive 32GB 2 in 1 OTG USB 3.0/Type C Thumb Drive Dual Drive USB C Memory Stick for Smartphone Laptop Tablet PC, Blue
  • 2 in 1: USB C + USB 3.0, 32GB usb c flash drive has dual ports, usb 3.0 port is applied to all devices which have usb 3.0 interface and usb c port is widely used in all Android smartphones with OTG function
  • High Speed USB 3.0: Read speed up to 90 MB/s, Write speed up to 30 MB/s, the speed of USB 3.0 interface is faster than USB 2.0, save time to wait, increases work productivity. Note: Speed will be limited if you use the USB key in the USB 2.0 interface
  • Large Compatibility: The USB 3.0 Connector is compatible with USB 3.0 & USB 2.0 backward USB 1.1 devices, such as Laptop, Desktop, Car Audio, Tablet, TV, Speakers, Projector. USB-C port is compatible with all Android Smartphones
  • Expand Storage: Good performance in storing, transferring and sharing digital data with families, friends, colleagues, customers. It can expand the capacity of smartphone, you can watch movies or share pictures when you go on vacation with your family
  • Note: Make sure your smartphone is equipped with OTG function and need to open OTG function in Settings when you plug memory stick, then you can transfer easily data bewteen different devices

Same-origin image

If the page and image share an origin (scheme, host and port), use the direct URL or convert it locally. No CORS option is needed.

Remote host you control

Configure the image server to return an appropriate Access-Control-Allow-Origin value, then load the image with CORS enabled:

html2canvas(document.querySelector('#capture'), {
  useCORS: true
}).then(function (canvas) {
  document.body.appendChild(canvas);
});

useCORS asks the browser to perform a CORS image load; it does not grant permission when the server omits the header.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Remote host you cannot change

Use a controlled, same-origin proxy that fetches an allowlisted remote image and returns it to your page with your origin. The html2canvas configuration supports a proxy option. Do not expose an unrestricted “fetch any URL” endpoint: validate destinations, restrict protocols and private-network addresses, limit response size, verify content type, and apply timeouts and rate limits. The project documents the proxy mechanism, not a particular proxy provider.

Why allowTaint is not a solution

The documented allowTaint option permits rendering conditions that may taint the canvas; it does not make a tainted canvas exportable. If you need a readable PNG or data URL, solve access with same-origin delivery, CORS, or a proxy.

Rank #3
Lexar D40E 64GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty

Waiting for several replacement images

When a capture contains multiple images, wait for every replacement to settle. Decide whether one failure should abort the operation or leave that image out:

function waitForImage(image, dataUrl) {
  return new Promise(function (resolve, reject) {
    let settled = false;
    function done(fn, value) {
      if (!settled) {
        settled = true;
        fn(value);
      }
    }
    image.addEventListener('load', function () { done(resolve, image); }, { once: true });
    image.addEventListener('error', function () {
      done(reject, new Error('Image failed to load: ' + image.src.slice(0, 80)));
    }, { once: true });
    image.src = dataUrl;
    if (image.complete) {
      image.naturalWidth > 0 ? done(resolve, image) : done(reject, new Error('Image decode failed'));
    }
  });
}

const replacements = [
  { element: document.querySelector('#hero'), dataUrl: heroDataUrl },
  { element: document.querySelector('#avatar'), dataUrl: avatarDataUrl }
];

Promise.all(replacements.map(function (item) {
  return waitForImage(item.element, item.dataUrl);
}))
  .then(function () {
    return html2canvas(document.querySelector('#capture'));
  })
  .then(function (canvas) {
    document.body.appendChild(canvas);
  })
  .catch(function (error) {
    console.error('Capture cancelled:', error);
  });

Useful html2canvas configuration

Verify defaults against the version installed in your project; documentation and defaults can change. The documented options most relevant to this problem are:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Option Purpose Important behavior
useCORS Attempt CORS image loading Default is false; server headers are still required.
proxy Route resource loading through a proxy Default is null; operate a restricted proxy.
allowTaint Allow potentially tainting resources Does not make export APIs work on a tainted canvas.
imageTimeout Maximum image wait Documented default is 15,000 milliseconds.
onclone Modify the cloned document before rendering Useful for temporary style or content changes.

See the project’s configuration reference for the release-specific list.

Exporting the captured canvas

The Base64 assigned to the source image and the output data URL are separate values. After html2canvas resolves, export the resulting canvas:

html2canvas(document.querySelector('#capture')).then(function (canvas) {
  const pngDataUrl = canvas.toDataURL('image/png');
  const link = document.createElement('a');
  link.href = pngDataUrl;
  link.download = 'capture.png';
  link.click();
});

This follows the output pattern shown in the official examples.

Rank #4
2-Pack 128GB USB C Flash Drive Dual Type C + USB A Memory Stick Jump Drive 2-in-1 Thumb Drive for Storage and Backup (128GB*2 Black&Blue)
  • 2-in-1 Dual Design: Features both USB-C and USB-A connectors, making it compatible with phones, tablets, MacBooks, PCs, and laptops-no adapter needed
  • Wide Compatibility: Works seamlessly with USB A and USB C devices, ensuring reliable file transfers across smartphones, computers, and more
  • Ample Storage Options: Available in 16GB/32GB/64GB/128GB providing plenty of space for photos, videos, music, and documents
  • Portable & Lightweight: Compact and durable design for travel, school, or daily use-take your files anywhere
  • Plug-and-Play Convenience: No software or drivers required; simply insert into USB-C or USB-A ports and start transferring files instantly

Troubleshooting checklist

The image area is blank

  • Confirm the value starts with data:image/... and contains ;base64,.
  • Inspect naturalWidth; zero indicates an invalid or undecodable payload.
  • Start html2canvas only after the replacement’s load event.
  • Check that CSS does not hide the element or give it zero dimensions.

SecurityError appears during export

A cross-origin resource tainted the canvas. Enable CORS only when the remote server sends the matching header, or deliver the image through a restricted same-origin proxy. Replacing the URL string with jQuery does not alter browser permissions.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

useCORS: true changes nothing

Inspect the image response in browser developer tools. If Access-Control-Allow-Origin is absent or incompatible, the browser will still block readable access. Correct the server configuration or use a proxy.

The capture times out

Large images, slow hosts and a low imageTimeout can delay rendering. Reduce source dimensions, preload images, or set a timeout appropriate for your application while retaining an explicit failure path.

Only some images render

Use a per-image load/error promise and log the failing URL. Choose an all-or-nothing policy with Promise.all, or use a settled-results approach if missing images are acceptable.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and security considerations

  • Base64 enlarges image data and duplicates it in memory when both the original and replacement remain referenced. Revoke unnecessary object URLs and release temporary data after capture.
  • Resize oversized source images before encoding; html2canvas must process the rendered pixel area.
  • Keep proxy allowlists narrow and reject redirects to untrusted destinations. Treat remote image bytes as untrusted input.
  • Do not put private credentials in a browser-visible image URL or data URL. Fetch protected assets through an authorized backend route.
  • Run capture work after the page has applied the final layout. Fonts, animations and lazy-loaded content can otherwise produce inconsistent output.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. It accepts a URL and returns PNG, JPEG, WebP or PDF, so you do not need to coordinate jQuery image replacement, browser CORS, or html2canvas rendering for a normal webpage capture. Cookie and consent banners, newsletter popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are not billed. AI agents can call its MCP tools, including take_screenshot, get_page_info and capture_pdf.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the API documentation at https://screenshotneo.com/docs/ for request details. A cURL request is:

Best Value
Samsung Type-C USB Flash Drive 256GB, USB 3.2 Gen 1, Up to 400MB/s
  • USB-C STORAGE ON THE GO: This sleek drive is supported by Samsung NAND flash and is incredibly compact to fit in the palm of your hand; Count on reliable performance and fast transfer speeds while staying compact
  • PERFORMANCE WITH SPEED: No need to choose between performance and reliability; Experience a fast, powerful flash drive that transfers 4GB files in just 11 seconds with up to 400MB/s USB 3.2 Gen 1 read speeds and is backward compatible with USB 3.0/2.0
  • MODERN MEETS ICONIC: The ultra-sleek USB-C drive looks as good as it performs; Featuring a reversible plug, the Type-C inserts into your devices seamlessly every time; Transfer large files with style and ease
  • ALWAYS CONNECTED: USB-C is compatible across devices, including laptops, tablets, phones and cameras, with enough space for 63,730 photos or maximum 12 hours of 4K video; With up to 256GB of storage space, this pocket-sized thumb drive comes in handy wherever you go
  • TOUGH & TRUSTED: Files stay secure, no matter the terrain; Samsung's flash memory technology makes the Type-C a trustworthy drive to store your valuable data; It's waterproof, shock-proof, magnet-proof, temperature-proof, and X-ray-proof body, plus it's backed by a 5-year limited warranty
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)
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}`);

Responses identify page and billing outcomes with X-Page-Verdict and X-Billed headers. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can I assign only the Base64 characters to src?

No. Include the complete data URL prefix, such as data:image/png;base64,, before the encoded bytes.

Does html2canvas capture browser pixels exactly?

No. It rebuilds a canvas from DOM and style information and supports only the features it understands.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use a proxy for every remote image?

No. Use direct same-origin delivery when possible, CORS when the image host allows it, and a restricted proxy only when the host cannot be changed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.