|
Hi,
I needed to be able to drag multiple targets, so modified Antoine's script accordingly (full source pasted below).
To drag an element using the newly modified script, the invocation would look like this:
<g id="graphic" onmousedown="setActive('graphic'); initDrag('graphic')" style="pointer-events: all">
If there are any problems with it, I'd love to know.
Thanks,
Patrick
p.s. I also removed references to items that were specific to Antoine's example, e.g. 'frame'.
/***************************************
*
* Author: Antoine Quint
* Article: Doing that drag thang
* http://www.xml.com/lpt/a/2002/02/27/drag.html
* Date: 24/02/2002
*
* Modified by Patrick Smith to support multiple targets
* 05/23/2003
*
***************************************/
// pointer to the root of the document
var root = document.documentElement;
// pointers to SVG elements we will access
var background = root.getElementById("background");
// SVGPoint to keep track of the offset of the dragging session
var offset = root.createSVGPoint();
// what element are we dragging?
var active;
// set our active element
function setActive(name) {
active = name;
}
// called on starting the drag
function initDrag (element) {
// what element are we dragging?
var target = root.getElementById(element);
// track the origin
var matrix = target.getCTM();
// get the relative position
var mouse = getMouse(evt);
offset.x = matrix.e - mouse.x;
offset.y = matrix.f - mouse.y;
// sets the new pointer-events
target.style.setProperty('pointer-events', 'none');
background.style.setProperty('pointer-events', 'all');
}
// called on dragging
function drag () {
// set target to active element
var target = root.getElementById(active);
// gets the pointer position
var mouse = getMouse(evt);
var x = mouse.x + offset.x;
var y = mouse.y + offset.y;
// updating the matrix
target.setAttribute('transform', 'translate(' + x + ',' + y + ')');
}
// called on finishing the drag
function endDrag () {
// set target to active element
var target = root.getElementById(active);
// resets the pointer-events
target.style.setProperty('pointer-events', 'all');
background.style.setProperty('pointer-events', 'none');
// reset active element to null
active = '';
}
// returns the mouse coordinates as an SVGPoint
function getMouse (evt) {
var position = root.createSVGPoint();
position.x = evt.clientX;
position.y = evt.clientY;
return position;
}
|