Rickard
Rickard

Reputation: 436

snap svg get viewBox

I have a simple SVG file containing a rectangle inlike this :

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

...and then, right before the closing </svg> tag I put this script :

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

I simply just want the alert box to display the current viewBox whenever I click on the rectangle, hovever, when I click the rectangle, the alert box just displays [object Object]

Any suggestion on how I should achieve this? How should I properly convert that [object Object] to a readable string?

Upvotes: 0

Views: 1582

Answers (1)

Bobby Orndorff
Bobby Orndorff

Reputation: 3335

The attr() function returns an object with properties that describe the viewbox. The object has x,y,width,height properties that are number values. The object has vb property that is a string value containing the x,y,width,height values.

Code using the x,y,width,height properties might look like...

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

Code using the vb property might look like...

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

Upvotes: 1

Related Questions