[英]Get width of svg element from uploaded file
I selected a svg file and read it via readDataUrl(<file>)
, I can set it to an html image element
by setting the src
to be the value read from the file. 我选择了一个svg文件,并通过readDataUrl(<file>)
读取,可以通过将src
设置为从文件读取的值来将其设置为html image element
。 However the width and height attributes will be 0. How can I set the value read from a file to an svg element
in order to be able to do a getBBox()
.width to obtain its width? 但是width和height属性将为0。如何设置从文件读取的值到svg element
,以便能够执行getBBox()
width来获取其宽度?
You can use XMLHttpRequest (or your favourite AJAX library) to read and parse the SVG file. 您可以使用XMLHttpRequest(或您最喜欢的AJAX库)来读取和解析SVG文件。 I imagine you can even just pass the dataurl to it if you want. 我想您可以根据需要甚至将dataurl传递给它。
Edit , because I misread the question : 编辑 , 因为我误解了问题:
readAsText()
method, then insert it in an html element. 如果可以将svg附加到文档中,并且需要使用FileReader,请使用其readAsText()
方法,然后将其插入html元素中。 function previewFile() { var file = document.querySelector('input[type=file]').files[0]; var reader = new FileReader(); reader.onloadend = function () { var parent = document.getElementById('container'); parent.innerHTML= reader.result; } if (file && file.type=="image/svg+xml") { reader.readAsText(file); } else { alert("wrong file type or no file provided"); } }
<div id="container"></div> <input type="file" onchange="previewFile()">
If you don't need to use a FileReader (eg if the file is saved on the server), Paul's answer is better. 如果您不需要使用FileReader(例如,如果文件保存在服务器上),Paul的答案会更好。
If you don't want to actually append the svg file but only know its width/height, you can refer to my 如果您不想实际附加svg文件,但只知道其宽度/高度,则可以参考我的
original answer : 原始答案:
I don't think you can get the height from the data url. 我认为您无法从数据网址获得高度。
As a workaround, you can use the readAsText()
method of the fileReader API, combined with the DOMParser()
method, in order to read the viewBox
property of the svg. 解决方法是,可以将readAsText()
API的readAsText()
方法与DOMParser()
方法结合使用,以读取svg的viewBox
属性。
function xlog(msg){ document.getElementById('log').textContent = msg; } function previewFile() { var file = document.querySelector('input[type=file]').files[0]; var reader = new FileReader(); reader.onloadend = function () { var doc = new DOMParser().parseFromString(reader.result, 'application/xml'); var viewBox = doc.documentElement.viewBox.baseVal; xlog('height:'+viewBox.height+' width:'+viewBox.width); } if (file && file.type=="image/svg+xml") { reader.readAsText(file); } else { xlog("wrong file type or no file provided"); } }
<p id="log"></p><br> <input type="file" onchange="previewFile()">
doc.documentElement
into your document and then get the element's BBox.
请注意,您可以将doc.documentElement
附加到文档中,然后获取元素的BBox。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.