[英]How to properly encode content of img src data:image/svg+xml?
假設我們有一個像這樣的簡單 SVG:
<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 text
</text>
</svg>
請注意“&”字符和“nbsp”HTML 實體。
這會產生這個圖像:
現在,如果我使用 encodeURIComponent 為我的圖像獲取正確的數據,我會得到:
%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
在 HTML 圖像中使用它 <img src="data:image/svg+xml,...,/> 圖像不會加載。
為了修復“nbsp”部分,我可以使用像他這樣的庫來解碼 HTML。 如果我刪除“&”,它會起作用。
但是“&”,即使我看到它被 %26 編碼,也會阻止圖像加載。
我不知道是否還有其他類似的字符會阻止圖像加載,所以我想知道我應該如何處理文本(可以是任何內容)以確保它始終正確呈現。
它不是有效的 XML。 您應該將&
替換為&
首先。 只有 5 個 XML 實體( <
、 >
、 &
、 "
、 '
)。 其他 HTML 實體根本不是 SVG 的一部分。 您可以替換
使用 unicode \
或 
或真正的 unicode 字符“”。
最終<text>
內容可以是以下內容之一
Some text & Other\u00A0text
Some text & Other text
Some text & 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, '&'); replaced.src = "data:image/svg+xml," + replacedSVG; </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.