How to parse SVG element's viewBox x, y, width and height values?

孤人 提交于 2020-01-30 07:40:28

问题


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.


回答1:


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>



回答2:


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);



回答3:


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>


来源:https://stackoverflow.com/questions/38428451/how-to-parse-svg-elements-viewbox-x-y-width-and-height-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!