如何查询snap svg事件对象以获取视图框坐标?

时间:2015-12-09 18:21:15

标签: javascript svg snap.svg

我有一个包含2个矩形和文本的简单svg文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg id="mySvg" onload="init()" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="100%" width="100%" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 1371.4286 773.5047">

<script xlink:href="snap.svg-min.js" type="text/ecmascript"/>
<rect id="blackRect" style="color-rendering:auto;color:#000000;isolation:auto;mix-blend-mode:normal;shape-rendering:auto;solid-color:#000000;image-rendering:auto" ry=".16344" height="773.5" width="1371.4" y="161.71" x="-371.43" fill="#ffb380"/>
<rect id="hoverTarget"   style="color-rendering:auto;color:#000000;isolation:auto;mix-blend-mode:normal;shape-rendering:auto;solid-color:#000000;image-rendering:auto" ry=".098402" height="177.14" width="286.62" y="369.51" x="180" fill="#008080"/>

<text id="viewboxText" style="word-spacing:0px;letter-spacing:0px" font-weight="bold" xml:space="preserve" font-size="27.5px" line-height="125%" y="810.93359" x="-3.165039e-005" font-family="sans-serif" fill="#000000"><tspan id="tspan3348" x="-3.165039e-005" y="810.93359">Viewbox :</tspan></text>
</svg>

在结束</svg>标记之前我添加了这个脚本:

<script><![CDATA[
var mySvg, hoverTarget,  viewboxText;
function init(){
  mySvg=Snap("#mySvg");
  hoverTarget=mySvg.select("#hoverTarget"); 
  viewboxText=mySvg.select("#viewboxText");
  hoverTarget.mousemove(hoverCursor);
}

function hoverCursor(evt){
  var cursorX, cursorY;
  if(evt.type==="mousemove"){
    cursorX=...;
     /*this is my question : how to interrogate the evt object to get X position of the cursor 
    according to mySvg viewbox?*/
    cursorY=...;
    //and, of course, how to get Y position from the evt object..

    //and after that, display it on the text...
    viewboxText.attr({text : "X : " + cursorX + ", Y : " + cursorY});
  }
}
]]></script>

我的问题是:有没有办法询问事件处理函数的snap事件对象以获取svg父元素的viewbox坐标?

如果有,那么语法是什么?

1 个答案:

答案 0 :(得分:0)

这就是我认为你可能会追随的......

首先我们得到从元素到屏幕的逆矩阵

var m = Snap.matrix( evt.target.getScreenCTM().inverse() )

// you may want to use this instead, but should be same for this case
// var m = Snap.matrix( mySvg.node.getScreenCTM().inverse() )

var newX = m.x( cursorX, cursorY )
var newY = m.y( cursorX, cursorY )

m.x(),m.y()将x,y坐标转换为新矩阵。

jsfiddle