bubkoo / html-to-image

✂️ Generates an image from a DOM node using HTML5 canvas and SVG.
MIT License
5.4k stars 505 forks source link

SVG symbols loose `currentColor` of the parent #394

Open snelsi opened 1 year ago

snelsi commented 1 year ago

Consider the following html:

<body>
  <!-- Turn this node to image -->
  <div id="target">
    <button style="color: red">
      <svg><use xlink:href="#icon" /></svg>
    </button>

    <button style="color: yellow">
      <svg><use xlink:href="#icon" /></svg>
     </button>
  </div>

  <!-- Global svg with symbols -->
  <svg style="display: none">
    <symbol id="icon" fill="none" viewBox="0 0 24 24">
      <path
        stroke="currentColor"
        d="M16 22v-4a4 4 0 0 0-8 0v4m13-11.85v7.82c0 2.22-1.8 4.03-4 4.03H7c-2.2 0-4-1.8-4-4.03v-7.82c0-1.21.54-2.36 1.47-3.12l5-4.12a3.97 3.97 0 0 1 5.06 0l5 4.12A4.05 4.05 0 0 1 21 10.15Z"
      />
    </symbol>
  </svg>
</body>

It should generate two buttons, one with red icon and one with yellow icon: image

But in the resulting image both icons are black:

image

Expected Behavior

Symbol Icons with currentColor should inherit color of the parent component where they are used.

Current Behavior

Svg symbol is inserted in the place where it's used, but the color of the body element is hardcoded in it's inline styles.

image

Possible Solution

Add an exception for this case here: https://github.com/bubkoo/html-to-image/blob/b751cbf212ccc7909077bc105b0630f9c845389a/src/clone-node.ts#L202

qq15725 commented 1 year ago

Fixed in my branch(commit)

Playground

snelsi commented 1 year ago

@qq15725 Sorry, but your fork doesn't handle svg symbols, if they are defined outside of the target element:

image

This makes it pretty much unusable for my use-case ☹️

qq15725 commented 1 year ago

Well, now it does 😄 see Import Map

snelsi commented 1 year ago

Oh, wow. Blasting speed! Will definitely try it later today 👍

snelsi commented 1 year ago

Looks like the original color issue still occurs. Can't reproduce it in a playground, though. But I keep getting wrong colored icons in my application