简体   繁体   中英

How to properly encode content of img src data:image/svg+xml?

Let's say we have a simple SVG like this:

<svg xmlns="http://www.w3.org/2000/svg" width="120" height="25">
    <rect x="0" y="0" width="120" height="25" stroke-wdith="1px" stroke="#000000" fill="#ffffff"/>
    <text x="60" y="15" stroke-width="0pt" font-family="arial,helvetica,sans-serif" font-size="11px" font-weight="normal" font-style="normal" text-decoration="none" display="inherit" text-anchor="middle">
        Some text & Other&nbsp;text
    </text>
</svg>

Notice the '&' caracters and the "nbsp" HTML entity.

This produce this image:

上面 SVG 的结果

Now if I use encodeURIComponent to get the proper data for my image, I get this:

%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120%22%20height%3D%2225%22%3E%3Crect%20x%3D%220%22%20y%3D%220%22%20width%3D%22120%22%20height%3D%2225%22%20stroke-wdith%3D%221px%22%20stroke%3D%22%23000000%22%20fill%3D%22%23ffffff%22%2F%3E%3Ctext%20x%3D%2260%22%20y%3D%2215%22%20stroke-width%3D%220pt%22%20font-family%3D%22arial%2Chelvetica%2Csans-serif%22%20font-size%3D%2211px%22%20font-weight%3D%22normal%22%20font-style%3D%22normal%22%20text-decoration%3D%22none%22%20display%3D%22inherit%22%20text-anchor%3D%22middle%22%3ESome%20text%20%26%20Other%26nbsp%3Btext%3C%2Ftext%3E%3C%2Fsvg%3E

Using this in an HTML image the <img src="data:image/svg+xml,...,/> the image won't load.

To fix the "nbsp" part, I can use a library like he to decode the HTML. If I remove the '&' it works.

But the '&', even if I see it gets encoded with %26, prevents the image from loading.

I don't know if there's other caracters like this that would prevent the image from loading so I'm wondering how I should deal with the text (which can be anything) to be sure it is always rendered properly.

It is not valid XML. You should replace & with &amp; in first place. There are only 5 XML entities ( &lt; , &gt; , &amp; , &quot; , &apos; ). Other HTML entities is not part of SVG at all. You can replace &nbsp; with unicode or &#160; or real unicode character " ".

Final <text> content can be one of

Some text &amp; Other\u00A0text
Some text &amp; Other&#160;text
Some text &amp; Other text

 <img id=replaced> <script> let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="300" height="150"> <rect width="100%" height="100%" stroke="#000" fill="#0f0"/> <text x="50%" y="50%" font-size="25px" text-anchor="middle"> Some text & Other text </text> </svg>`; let replacedSVG = svg.replace(/#/g, '%23') .replace(/"/g, "'") .replace(/&/g, '&amp;'); replaced.src = "data:image/svg+xml," + replacedSVG; </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM