在SVG View下整图平移

来源:互联网 发布:数据库外键是什么 编辑:程序博客网 时间:2024/06/06 09:27

      今天在网上查询在SVGView下对SVG图形进行平移操作的JS代码时发现了有不少对SVG图形中某些图元进行移动的文档,而没有整图平移的代码。

      参考这些代码,自己写了整图平移的代码。

      代码如下(记得将下面代码保存成UTF-8编码格式的svg文件):

<?xml version='1.0' standalone='no'?>

<svg width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'

onload='Init(evt)' onmousedown='Grab(evt)' onmousemove='Drag(evt)'

onmouseup='Drop(evt)'>

<title>Drag And Drop</title>

<desc>

A nice little demo of drag-and-drop functionality in SVG,

written by Doug Schepers on February 16, 2004. Use or misuse

this code however you wish.

</desc>

<script type="text/javascript"><![CDATA[

var svgdoc = null; // SVG文档对象

var svgroot = null; // SVG文档的根节点

var check = false; // 图像拖动标志

var TrueCoords = null; // 

var GrabPoint = null;

var BackDrop = null; // 背景对象

var WholeMap = null; // 整图对象

/**

 * @功能: 初始化函数

 **/

function Init(evt) {

svgdoc = evt.target.ownerDocument;

svgroot = svgdoc.documentElement;

 

TrueCoords = svgroot.createSVGPoint();

GrabPoint = svgroot.createSVGPoint();

BackDrop = svgdoc.getElementById('BackDrop');

WholeMap = svgdoc.getElementById('whole');

}

 

/**

 * @功能:处理鼠标落下的事件

 * @param evt:事件句柄

 **/

function Grab(evt) {

if (evt.button != 0) {

// 非左键不响应

return;

}

var transMatrix = WholeMap.getCTM();

GrabPoint.x = TrueCoords.x - Number(transMatrix.e);

GrabPoint.y = TrueCoords.y - Number(transMatrix.f);

check = true;

// alert(GrabPoint.x+":"+GrabPoint.y);

}

 

/**

 * @功能:处理鼠标移动事件

 * @param evt:事件句柄

 **/

function Drag(evt) {

GetTrueCoords(evt);

 

if (check == true) {

var newX = TrueCoords.x - GrabPoint.x;

var newY = TrueCoords.y - GrabPoint.y;

 

WholeMap.setAttributeNS(null, 'transform', 'translate(' + newX + ','

+ newY + ')');

}

}

 

/**

 * @功能:处理鼠标松开事件

 * @param evt:事件句柄

 **/

function Drop(evt) {

check = false;

}

 

/**

 * @功能:获取鼠标移动位置

 * @param evt:事件句柄

 **/

function GetTrueCoords(evt) {

var newScale = svgroot.currentScale;

var translation = svgroot.currentTranslate;

TrueCoords.x = (evt.clientX - translation.x) / newScale;

TrueCoords.y = (evt.clientY - translation.y) / newScale;

};

   ]]></script>

 

<rect id='BackDrop' x='-10%' y='-10%' width='110%' height='110%'

fill='none' pointer-events='all' />

 

<g id="whole">

<circle id='BlueCircle' cx='25' cy='25' r='20' style='fill:blue; ' />

<circle id='RedCircle' cx='125' cy='25' r='20' style='fill:red; ' />

<circle id='OrangeCircle' cx='225' cy='25' r='20'

style='fill:orange; ' />

<text id='DraggableText' x='20' y='200'

style='fill:red; font-size:18px; font-weight:bold;'>

Draggable Text

</text>

 

<rect id='GreenRectangle' x='50' y='70' width='100' height='100'

style='fill:green; ' />

 

<g id='Folder'>

<rect id='FolderRectangle' x='300' y='100' width='200'

height='150' style='fill:tan; stroke:brown; stroke-width:3;' />

</g>

</g>

</svg>