snap svg get viewBox

时间:2015-12-03 17:04:06

标签: javascript svg snap.svg

我有一个包含矩形的简单SVG文件:

<svg id="mySvg" onload="init()" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="297mm" viewBox="0 0 744.09448819 1052.3622047" width="210mm" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/">
<metadata id="metadata892">
  <rdf:RDF>
  <cc:Work rdf:about="">
  <dc:format>image/svg+xml</dc:format>
  <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
  <dc:title/>
  </cc:Work>
  </rdf:RDF>
</metadata>
<script xlink:href="snap.svg-min.js" type="text/ecmascript"/>
<rect id="myRect" opacity="1"  rx="28.143" ry="37.785" height="225.71" width="365.21" y="260.93" x="94.286"/>
</svg>

...然后,在结束</svg>标记之前我放了这个脚本:

<script><![CDATA[
var mySvg, myRect;

function init(){
  mySvg=Snap("#mySvg");
  myRect=mySvg.select("#myRect");
  myRect.click(rectCursor);
}

function rectCursor(evt){
  if(evt.type==="click"){
  alert(mySvg.attr("viewBox"));
}

]]></script>

我只是希望警报框在我点击矩形时显示当前的viewBox,当我点击矩形时,警告框只显示[object Object]

关于我应该如何实现这一点的任何建议?我该如何将[object Object]正确转换为可读字符串?

1 个答案:

答案 0 :(得分:0)

attr()函数返回一个对象,该对象具有描述视图框的属性。对象具有x,y,width,height属性,这些属性是数值。该对象具有vb属性,该属性是包含x,y,width,height值的字符串值。

使用x,y,width,height属性的代码可能看起来像......

var viewBox = mySvg.attr("viewBox");
alert(viewBox.x + " " + viewBox.y + " " + viewBox.width + " " + viewBox.height);

使用vb属性的代码可能看起来像......

alert(mySvg.attr("viewBox").vb);