我找到了一種將影像從用戶檔案系統轉換為 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()
}
}
該影像很好地附加在需要的位置:

問題是這個影像沒有出現在螢屏上,非常奇怪的部分是我可以讓它從 devtool 中出現,復制<image>元素,從父級“編輯為 HTML”<g id="logo_group">"并將其粘貼到里面的任何地方。之后,原始和粘貼的一個出現在螢屏上,如果我洗掉一個或另一個,最后一個仍然出現..
為什么 ?我該怎么做才能讓它首先出現?
uj5u.com熱心網友回復:
您需要將 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 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/505827.html
標籤:javascript 图片 svg base64 文件阅读器
上一篇:需要幫助在tkinterPython中制作隨機影像選擇器
下一篇:顯示意外行為的錨點
