[英]Strange bug converting images into Base64 string for SVG element
我找到了一種將用戶文件系統中的圖像轉換為 Base64 字符串以將其添加到 SVG 元素的方法:
const importLogo = document.querySelector('input#import-logo')
function encodeImageFileAsURL(){ // Fired onchange from the input element html
var file = importLogo.files[0]
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
let logoImg = document.createElement('image')
logoImg.setAttribute('xlink:href', reader.result)
logoImg.setAttribute('height', '1000')
logoImg.setAttribute('width', '3000')
logoImg.setAttribute('x', '0')
logoImg.setAttribute('y', '0')
clickedLogoElement.parentNode.appendChild(logoImg)
clickedLogoElement.remove()
}
}
該圖像很好地附加在需要的位置:
問題是這個圖像沒有出現在屏幕上,非常奇怪的是我可以從開發工具中讓它出現,從父<g id="logo_group">"
復制<image>
元素,“編輯為 HTML” <g id="logo_group">"
並將其粘貼到里面的任何位置。之后,原始和粘貼的一個出現在屏幕上,如果我刪除一個或另一個,最后一個仍然出現..
為什么? 我該怎么做才能讓它首先出現?
您需要將 svg 和 xlink 命名空間與 SVG 一起使用。 所有元素都在 svg 命名空間中,並且 xlink:href 屬性在 xlink 命名空間中。
因此,您需要對代碼進行以下更改:
let logoImg = document.createElementNS('http://www.w3.org/2000/svg', 'image')
logoImg.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', reader.result)
盡管現在大多數瀏覽器都支持 null 命名空間中的 href。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.