How to parse SVG element's viewBox x, y, width

2020-04-16 17:38发布

Suppose I have an SVG element :

<svg id="myMap" viewBox="0 0 200 200"></svg>

How would I get get a specific value of myMap's viewBox? For a simplified example : how to get the "x" value of the viewBox attribute of myMap? (for the above example, the x value is the first zero (0)).

Below is some variation of syntax I've tried :

<script>
  var myMap = Snap("#myMap");
  alert(myMap.attr("viewBox"));//dislays [object Object]
  alert(myMap.attr("viewBox.vbx"));//also dislays [object Object]
  alert(myMap.attr("viewBox.x"));//also dislays [object Object]
</script>

All the above examples display [object Object] on the alert box.
I need the proper float value of x, y, width and height of the viewport to implement zoom in and out functions in a map.

标签: svg snap.svg
3条回答
仙女界的扛把子
2楼-- · 2020-04-16 17:57

Thank you, @Robert Longson

alert(document.getElementById("myMap").viewBox.baseVal.width);
<svg id="myMap" viewBox="0 0 200 200"></svg>

alert(document.getElementById("myMap").viewBox.baseVal.width);
<svg id="myMap" viewBox="0 0 200 200"></svg>

查看更多
放荡不羁爱自由
3楼-- · 2020-04-16 17:58

You could always just read it straight out of the DOM

alert(document.getElementById("myMap").viewBox.baseVal.width);
<svg id="myMap" viewBox="0 0 200 200"></svg>

查看更多
仙女界的扛把子
4楼-- · 2020-04-16 18:09

The attr() method returns an object instead of a scalar, while alert() needs a scalar. If you use console.log() instead of alert() you can see the contents of the objects in your JavaScript console.

To get x, y, width and height of your svg use

var myMap = Snap("#myMap");
var attrs = myMap.attr("viewBox");

console.log(attr.x);
console.log(attr.y);
console.log(attr.width);
console.log(attr.height);
查看更多
登录 后发表回答