How to Include CSS style when converting svg to png

后端 未结 1 541
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 15:30

i\'ve created a simple SVG elment that get dowbloaded to png when clicking on a button, my solution is similiar to here


The basic idea is:
1.svg to canvas<

相关标签:
1条回答
  • 2020-11-30 16:09

    Question 1 (first half): what's the real reason (is the GPU acceleration related in anyway?)

    No, GPU acceleration has nothing to do with it.
    The broadest reason is privacy.

    To draw your svg with drawImage you have to load your svg as an external document inside an <img> tag. SVG can be quite a complex image format for resources loading (it can literally require any kind of resource that could be required by any HTML document). Thus, it has been stated in specs that the same security as the one for <iframe> elements or <object> or similar ones should apply to <img> content and even stricter :

    <img> content can not require any external resources, nor access to the main document.

    Question 1 (second half): and the solution for this issue

    You pointed to some SO questions already answering it, you could also just include all the stylesheets from the main document inside a <style> tag inside your parsed svg Node, before you do create the Blob from it. dumb implementation here

    Question 2 : "how i still overcome this issue when using a custom font with Fontface"

    For external resources, you have to encode it as dataURI, and include it in your svg node before you create the Blob. For font in particular, you'd set a font-face property in a <style> element.

    So at the end, your svg would have something like

    <defs>
      <style>
        /* all your parsed styles in here */
        @font-face {
         font-family: foo;
         src: url('data:application/font-woff;charset=utf-8;base64,...')
        }
      </style>
    </defs>
    

    in itself before you do extract its markup.

    0 讨论(0)
提交回复
热议问题