User Agents

Web browsers and everyday web tech, explained

Fix dom-to-image in Safari with Multiple Images

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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).
  2. 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(), sets crossOrigin = 'anonymous' (if needed), and resolves with the data URL after loading. Use canvas.toDataURL('image/png') to convert the loaded image.
  3. Preload all images before calling dom-to-image. Use Promise.all to wait for all images to be converted to data URLs. This ensures Safari doesn't try to render images that aren't fully loaded.
  4. Replace the src attributes with the data URLs. After preloading, iterate through the original img elements and set their src to the corresponding data URL. Do this on a clone of the element to avoid mutating the original DOM.
  5. 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.
  6. Call dom-to-image on the clone. Pass the cloned element to domToImage.toPng() or toJpeg(). This avoids issues with the original element's live state.
  7. 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.
  8. Handle fonts and external resources. If you're using web fonts, they may not be loaded when the capture happens. Use document.fonts.ready to 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 set crossOrigin='anonymous' on the server side or proxy the images.
  • Mutating the original DOM. Replacing src on the original element can break your page. Always work on a clone.
  • Forgetting to handle background images. dom-to-image may not capture CSS background images reliably in Safari. You may need to convert them to img elements or use a different library.
  • Calling dom-to-image immediately after page load. Safari might not have painted everything yet. Use a small delay or wait for requestAnimationFrame.

Tips

  • Use a high-quality data URL format. For PNG, use image/png; for JPEG, use image/jpeg with 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 set background-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.log inside the onload handler 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 set crossOrigin before setting src.
  • Images appear but are blurry or distorted. The canvas size might be off. Use width and height attributes on the original images. Also, check dom-to-image options like width and height.
  • Fonts don't render. Wait for document.fonts.ready before 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.