Fix dom-to-image in Safari with Multiple Images
In this article
If you're using dom-to-image to capture a DOM element as a PNG and it fails or produces a blank image in Safari—especially when multiple images are involved—the root cause is almost always Safari's handling of SVG foreignObject and image loading. This guide walks you through a reliable fix: preloading images, converting them to data URLs, and ensuring they're fully loaded before rendering. No extra libraries are needed.
What You'll Need
- Basic familiarity with JavaScript and Promises
- Your existing project using
dom-to-image - A way to test in Safari (e.g., Safari on macOS or iOS simulator)
Step-by-Step
- Identify all images in the target element. Use
element.querySelectorAll('img')to get every image. Also check for CSS background images—those are trickier and may need a different approach (see Tips). - Create a function to preload an image and return a data URL. Write an async function that takes an image URL, creates a new
Image(), setscrossOrigin = 'anonymous'(if needed), and resolves with the data URL after loading. Usecanvas.toDataURL('image/png')to convert the loaded image. - Preload all images before calling
dom-to-image. UsePromise.allto wait for all images to be converted to data URLs. This ensures Safari doesn't try to render images that aren't fully loaded. - Replace the
srcattributes with the data URLs. After preloading, iterate through the originalimgelements and set theirsrcto the corresponding data URL. Do this on a clone of the element to avoid mutating the original DOM. - Clone the target element and inject the data URLs. Use
element.cloneNode(true)to get a deep clone. Then replace the image sources in the clone. - Call
dom-to-imageon the clone. Pass the cloned element todomToImage.toPng()ortoJpeg(). This avoids issues with the original element's live state. - Ensure the clone is attached to the DOM (or not). In some Safari versions, the clone must be in the document for images to render. If you get a blank output, try appending the clone to the body (hidden) before calling
dom-to-image, then remove it after. - Handle fonts and external resources. If you're using web fonts, they may not be loaded when the capture happens. Use
document.fonts.readyto wait for fonts before rendering.
Common Mistakes
- Not waiting for images to load. Safari often fails silently if images are still loading. Always preload and await.
- Using cross-origin images without CORS. If the image is on another domain and doesn't send CORS headers,
canvas.toDataURL()will throw a security error. You must either setcrossOrigin='anonymous'on the server side or proxy the images. - Mutating the original DOM. Replacing
srcon the original element can break your page. Always work on a clone. - Forgetting to handle background images.
dom-to-imagemay not capture CSS background images reliably in Safari. You may need to convert them toimgelements or use a different library. - Calling
dom-to-imageimmediately after page load. Safari might not have painted everything yet. Use a small delay or wait forrequestAnimationFrame.
Tips
- Use a high-quality data URL format. For PNG, use
image/png; for JPEG, useimage/jpegwith a quality parameter (e.g., 0.9). - Cache the data URLs. If you're capturing the same element multiple times, store the data URLs to avoid re-converting images.
- Test on both macOS and iOS Safari. They behave slightly differently; iOS Safari is often more restrictive.
- Consider using
dom-to-image-more. This fork fixes many Safari issues, including better handling of images and fonts. If you're free to change libraries, it's a solid alternative. - For background images, inline them as
data:URLs in the style attribute. You can fetch the background image, convert it, and setbackground-image: url(data:...)on the clone.
Troubleshooting
- Blank output or black rectangle. This usually means images aren't loaded. Double-check that your preloading function actually resolves. Add a
console.loginside theonloadhandler to verify. - SecurityError: The operation is insecure. This is a CORS issue. Ensure the image server sends
Access-Control-Allow-Origin: *(or your domain). Also, you must setcrossOriginbefore settingsrc. - Images appear but are blurry or distorted. The canvas size might be off. Use
widthandheightattributes on the original images. Also, checkdom-to-imageoptions likewidthandheight. - Fonts don't render. Wait for
document.fonts.readybefore capturing. Also, ensure the font is loaded on the clone—if you append the clone to the DOM, the fonts should inherit. - Large images cause memory issues. Downscale the images before converting to data URLs by drawing them to a smaller canvas.
Frequently Asked Questions
Why does dom-to-image work in Chrome but not Safari?
Safari has stricter security and rendering rules for foreignObject in SVG. It often fails to load images that are not fully cached or that lack CORS headers. Preloading and converting to data URLs bypasses these restrictions.
Can I use data URLs for all images?
Yes, but data URLs increase the size of the HTML string. For large images, consider using JPEG data URLs to reduce size.
Do I need to set crossOrigin on every image?
Only for images from a different origin. If the image is same-origin, you can skip it. But setting it doesn't hurt.
Will this work with CSS background images?
Not automatically. You need to manually convert background images to data URLs and set them on the clone's style. The steps are similar: fetch the image, convert, and replace the background-image property.
Is there a simpler alternative to dom-to-image?
Yes, html2canvas is another popular library. However, it has its own quirks with Safari. The preloading approach works with it too.
Can I capture multiple elements at once?
You can capture each element separately and then combine the resulting images on a canvas. But if you need a single image of multiple elements, wrap them in a container and capture that container.