最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get size of SVG graphics by javascript - Stack Overflow

programmeradmin4浏览0评论

To add a svg graphics in html page, it is mon to use object tag to wrap it like this:

<object id="svgid" data="mysvg.svg" type="image/svg+xml" 
  wmode="transparent" width="100" height="100">

this browser is not able to show SVG: <a linkindex="3"
href="">;/a> 
is free and does it!
If you use Internet Explorer, you can also get a plugin: 
<a linkindex="4" href=".html">
.html</a>

</object>

If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?

To add a svg graphics in html page, it is mon to use object tag to wrap it like this:

<object id="svgid" data="mysvg.svg" type="image/svg+xml" 
  wmode="transparent" width="100" height="100">

this browser is not able to show SVG: <a linkindex="3"
href="http://getfirefox.">http://getfirefox.</a> 
is free and does it!
If you use Internet Explorer, you can also get a plugin: 
<a linkindex="4" href="http://www.adobe./svg/viewer/install/main.html">
http://www.adobe./svg/viewer/install/main.html</a>

</object>

If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?

Share Improve this question asked Oct 23, 2008 at 21:51 David.Chu.caDavid.Chu.ca 38.7k65 gold badges152 silver badges198 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 10

See http://dev.opera./articles/view/svg-evolution-not-revolution/?page=2

It is possible to get access to the SVG DOM referenced by an HTML:object as long as the SVG file is on the same domain (otherwise this would be a security vulnerability. If your object tag has id="myobj" you would do:

var obj = document.getElementById("myobj"); // reference to the object tag
var svgdoc = obj.contentDocument; // reference to the SVG document
var svgelem = svgdoc.documentElement; // reference to the SVG element

Then you can get access to the svg element's width/height by:

svgelem.getAttribute("width")
svgelem.getAttribute("height")

Note that these attributes may be things like "100px", "300", "200em", "40mm", "100%" so you need to carefully parse it.

> Is there any way to get svg's size by using JavaScript?

No and yes.

No:

JavaScript won't be able to access the SVG file contents that are sitting in the browser.

So it wouldn't be possible to have a page containing an arbitrary SVG image and then have JavaScript determine anything from the SVG file itself.

The only data JS can access it that contained within the page's DOM: the original markup plus any JS-related modifications to the DOM. You could access the object element's attributes and descendant nodes, but that won't give you visibility of anything more than what you can see if you look at the page markup yourself.

Yes:

JS (in modern browsers) can parse any XML string into a DOM and then access the content using DOM-based methods.

You could get the SVG file contents by issuing an xmlHttpRequest-style request (i.e. JS performs an HTTP GET on the SVG file's URL). JS would then have the SVG file's full XML string and you can then access anything you like.

> Or maybe I should just look at the svg xml file to find out the size from the top svg tag?

This would be more feasible by far.

The only JS-based solution would require JS to perform a GET request on the SVG file's URL (as above), which is unlikely to be feasible - each page load might result in double-downloading each SVG file, and the parsing of the SVG's XML into a DOM by JS might be too resource intensive.

Having JS retrieve the SVG's XML content and parse it into a DOM to retrieve only the image dimensions is a bit overkill. It's perfectly possible, but generally not practical.

Querying the SVG's XML content server-side, determining a suitable width and height and then dynamically adding the width and height attributes prior to returning markup to the browser would be your best bet.

ES6: Using async/await you can do this in sequence-like way

async function getImage(url) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = url;
    });
}

and use above function

let img = await getImage("yourimage.svg");
let w = img.width;
let h = img.height; 

You can use it as long as the SVG file is on the same domain (details here). Working example

async function getImage(url) {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = url;
  });
}

async function start() {
  // here is example url with embeded svg but you can use any url
  let svgURL = "data:image/svg+xml,%3Csvg xmlns='http://www.w3/2000/svg' height='120' width='220'%3E%3Cellipse cx='110' cy='60' rx='100' ry='50' stroke='black' stroke-width='3' fill='red' /%3E%3C/svg%3E";
  
  let img = await getImage(svgURL);
  let w = img.width;
  let h = img.height; 
  
  // print
  console.log({w,h});
  pic.src = svgURL;
}

start();
<img id="pic">

Is there any way to get svg's size by using JavaScript?

YES

var filesize = function(url, requestHandler) {
  var requestObj = new XMLHttpRequest();  
  requestObj.open('head', address, true);  
  requestObj.onreadystatechange = callback;
  requestObj.send(null);  
};

Now a handling function:

var requestHandler = function(result) {
    if (this.readyState === 1) {
        this.abort();
    }
    return this.getResponseHeader("Content-length");
};

var size = fileSize("http://whatever/someSVGFile.svg", requestHandler);
alert(size); 

That should return the filesize of your svg or any other file without a hitch. Server configuration is the only thing that might interfere.

发布评论

评论列表(0)

  1. 暂无评论