Skip to content

Instantly share code, notes, and snippets.

@mvanlonden
Created October 17, 2013 16:02
Show Gist options
  • Save mvanlonden/7027576 to your computer and use it in GitHub Desktop.
Save mvanlonden/7027576 to your computer and use it in GitHub Desktop.
jquery-svgpandragsnap
<!DOCTYPE HTML>
<html>
<head>
<!-- jQuery -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- d3 -->
<script type="text/javascript" src="http://d3js.org/d3.v2.js"></script>
<script type="text/javascript" src="jquery-svgpan.js"></script>
<title>jquery-svgpan Demo</title>
<style type="text/css">
body {
font-family: Helvetica, sans-serif;
}
#instructions {
border: 1px solid #aaa;
margin: .5em;
padding: .5em;
}
svg {
border: 1px solid #aaa;
overflow: hidden; /* Thanks IE9! */
}
a:link {
color: #aaa;
}
a:visited {
color: #aaa;
}
div { margin-top: 0.5em; margin-right: 0.5em; margin-bottom: 0.5em; margin-left: 0.5em; padding-top: 0.5em; padding-right: 0.5em; padding-bottom: 0.5em; padding-left: 0.5em; }
div#mouse { display: none; position: absolute; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: white; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: black; border-right-color: black; border-bottom-color: black; border-left-color: black; border-image: initial; background-position: initial initial; background-repeat: initial initial; }
div#visuals { float: left; }
div#request { position: absolute; top: 1em; right: 1em; width: 200px; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: rgb(153, 153, 153); border-right-color: rgb(153, 153, 153); border-bottom-color: rgb(153, 153, 153); border-left-color: rgb(153, 153, 153); border-image: initial; }
textarea { width: 100%; height: 8em; }
.node { font: normal normal normal 8px/normal sans-serif; }
.node circle { fill: #ffffff; stroke-width: 1.5px; stroke: #000000; }
.node.branch circle { stroke: #808080; }
.node.found circle { stroke: #4682b4; }
.node.loaded circle { stroke: #008000; }
.node.wait circle { stroke: #ff0000; stroke-width: 3px; cursor: pointer; }
.node.missing circle { stroke: #ffa500; }
.node.failed circle { stroke: #ffa500; }
path { fill: none; stroke: #cccccc; stroke-width: 1.5px; }
</style>
</head>
<body>
<div id="instructions">
<div>
Click and drag to pan. Use the scroll wheel to zoom. Each SVG works separately.
</div>
<div>
The voronoi code is adapted
from <a href="http://mbostock.github.com/d3/ex/voronoi.html">this
example</a>, to demonstrate panning and zooming SVG content
generated dynamically using
the <a href="http://mbostock.github.com/d3/">d3
visualization</a> library. A g root element was added for a viewport.
</div>
</div>
<div>
<svg width="960" height="500" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink"><g id="viewport" transform="matrix(0.9240345346828462,0,0,0.9240345346828462,427.4995349244402,399.0884233275848)"><rect x="70" width="300" height="100"
style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)"/><circle cx="0" cy="0" r="40" stroke="black"
stroke-width="2" fill="red"/></g></svg>
</div>
<div id="chart"></div>
<script type="text/javascript">
$(document).ready(function() {
var w = 960,
h = 500;
var vertices = d3.range(100).map(function(d) {
return [Math.random() * w, Math.random() * h];
});
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("class", "PiYG")
.on("mousemove", update);
// This was added to the example
var g = svg.append('g')
.attr('id', 'viewport');
g.selectAll("path")
.data(d3.geom.voronoi(vertices))
.enter().append("path")
.attr("class", function(d, i) { return i ? "q" + (i % 9) + "-9" : null; })
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });
g.selectAll("circle")
.data(vertices.slice(1))
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 2);
function update() {
// Make sure to filter the mouse event to D3 through our SVGPan
// transformation
var p = this.createSVGPoint();
p.x = d3.mouse(this)[0];
p.y = d3.mouse(this)[1];
p = p.matrixTransform(this.getElementById("viewport").getCTM().inverse());
vertices[0] = [p.x, p.y];
g.selectAll("path")
.data(d3.geom.voronoi(vertices)
.map(function(d) { return "M" + d.join("L") + "Z"; }))
.filter(function(d) { return this.getAttribute("d") != d; })
.attr("d", function(d) { return d; });
}
$('svg').svgPan('viewport');
});
</script>
</body>
</html>
/**
THIS LICENSE IS FOR JQUERY-SVGPAN. The original SVGPan library,
from which it derived, is governed by the second license below.
Copyright 2012 John Krauss. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY JOHN KRAUSS ''AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL JOHN KRAUSS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
The views and conclusions contained in the software and
documentation are those of the authors and should not be
interpreted as representing official policies, either expressed or
implied, of John Krauss.
**/
// SVGPan library 1.2.2 license and documentation:
/**
* SVGPan library 1.2.2
* ======================
*
* Given an unique existing element with id "viewport" (or when missing, the
* first g-element), including the the library into any SVG adds the following
* capabilities:
*
* - Mouse panning
* - Mouse zooming (using the wheel)
* - Object dragging
*
* You can configure the behaviour of the pan/zoom/drag with the variables
* listed in the CONFIGURATION section of this file.
*
* Known issues:
*
* - Zooming (while panning) on Safari has still some issues
*
* Releases:
*
* 1.2.2, Tue Aug 30 17:21:56 CEST 2011, Andrea Leofreddi
* - Fixed viewBox on root tag (#7)
* - Improved zoom speed (#2)
*
* 1.2.1, Mon Jul 4 00:33:18 CEST 2011, Andrea Leofreddi
* - Fixed a regression with mouse wheel (now working on Firefox 5)
* - Working with viewBox attribute (#4)
* - Added "use strict;" and fixed resulting warnings (#5)
* - Added configuration variables, dragging is disabled by default (#3)
*
* 1.2, Sat Mar 20 08:42:50 GMT 2010, Zeng Xiaohui
* Fixed a bug with browser mouse handler interaction
*
* 1.1, Wed Feb 3 17:39:33 GMT 2010, Zeng Xiaohui
* Updated the zoom code to support the mouse wheel on Safari/Chrome
*
* 1.0, Andrea Leofreddi
* First release
*
* This code is licensed under the following BSD license:
*
* Copyright 2009-2010 Andrea Leofreddi <a.leofreddi@itcharm.com>. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY Andrea Leofreddi ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Andrea Leofreddi OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Andrea Leofreddi.
*/
/*global define, jQuery, window*/
(function (factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
"use strict";
var NONE = 0,
PAN = 1,
DRAG = 2,
init = function (root, svgRoot, enablePan, enableZoom, enableDrag, zoomScale, enableSnap, gridSize) {
var state = NONE,
stateTarget,
stateOrigin,
stateTf,
svgDoc = root,
$root = $(root),
$parent = $root.parent(),
recentOffset = $root.offset(),
// FF sometimes doesn't calculate this anything near correctly
// for SVGs.
offsetIsBroken = Math.abs($root.offset().left) > 1e5,
isMouseOverElem = false,
/**
* Dumps a matrix to a string (useful for debug).
*/
dumpMatrix = function (matrix) {
var s = "[ " + matrix.a + ", " + matrix.c + ", " + matrix.e + "\n " + matrix.b + ", " + matrix.d + ", " + matrix.f + "]";
return s;
},
/**
* Instance an SVGPoint object with given event coordinates.
*/
getEventPoint = function (evt) {
var p = root.createSVGPoint(),
offsetX = evt.offsetX,
offsetY = evt.offsetY,
offset,
ctm,
matrix;
if (typeof offsetX === "undefined" || typeof offsetY === "undefined") {
offset = offsetIsBroken ? $parent.offset() : recentOffset;
offsetX = evt.pageX - offset.left;
offsetY = evt.pageY - offset.top;
}
p.x = offsetX;
p.y = offsetY;
return p;
},
/**
* Sets the current transform matrix of an element.
*/
setCTM = function (element, matrix) {
var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
element.setAttribute("transform", s);
},
/**
* Handle mouse wheel event.
*/
handleMouseWheel = function (evt) {
if (!enableZoom) {
return;
}
if (!isMouseOverElem) {
return;
}
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
recentOffset = $root.offset();
var delta = evt.wheelDelta ? evt.wheelDelta / 360 : evt.detail / -9,
z = Math.pow(1 + zoomScale, delta),
g = svgRoot,
p = getEventPoint(evt),
k;
p = p.matrixTransform(g.getCTM().inverse());
// Compute new scale matrix in current mouse position
k = root.createSVGMatrix().translate(p.x, p.y).scale(z).translate(-p.x, -p.y);
setCTM(g, g.getCTM().multiply(k));
if (typeof stateTf === "undefined") {
stateTf = g.getCTM().inverse();
}
stateTf = stateTf.multiply(k.inverse());
},
/**
* Handle mouse move event.
*/
handleMouseMove = function (evt) {
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
var g = svgRoot,
p;
if (state === PAN && enablePan) {
// Pan mode
p = getEventPoint(evt).matrixTransform(stateTf);
setCTM(g, stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y));
} else if (state === DRAG && enableDrag) {
// Drag mode
p = getEventPoint(evt).matrixTransform(g.getCTM().inverse());
setCTM(stateTarget, root.createSVGMatrix().translate(p.x - stateOrigin.x, p.y - stateOrigin.y).multiply(g.getCTM().inverse()).multiply(stateTarget.getCTM()));
stateOrigin = p;
}
},
/**
* Handle mouseenter event. This has been added to stop ignoring
* inputs when the mouse is over the element.
**/
handleMouseEnter = function (evt) {
// bind our mousemove listener only when we have mouse in view
if (!isMouseOverElem) {
recentOffset = $root.offset();
$root.bind('mousemove', handleMouseMove);
isMouseOverElem = true;
}
},
/**
* Handle mouseleave event. This has been added to ignore
* inputs when the mouse is not over the element.
**/
handleMouseLeave = function (evt) {
// unbind our mousemove listener only when we no longer have mouse in view
if (isMouseOverElem) {
$root.unbind('mousemove', handleMouseMove);
isMouseOverElem = false;
}
state = NONE;
},
/**
* Handle click event.
*/
handleMouseDown = function (evt) {
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
//var svgDoc = evt.target.ownerDocument;
//var g = getRoot(svgDoc);
var g = svgRoot;
// Pan anyway when drag is disabled and the user clicked on an element
if (evt.target.tagName === "svg" || !enableDrag) {
// Pan mode
state = PAN;
stateTf = g.getCTM().inverse();
stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
} else {
// Drag mode
state = DRAG;
stateTarget = evt.target;
stateTf = g.getCTM().inverse();
stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
}
},
/**
* Rounding function for x and y coordinate of evt.target.
* Called on mouse up.
**/
snap = function (value, gridSize, roundFunction) {
if (roundFunction === undefined) roundFunction = Math.round;
var snaptrans = (gridSize * roundFunction(value / gridSize)) - value;
return snaptrans;
},
/**
* Handle mouse button release event.
*/
handleMouseUp = function (evt) {
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
//var svgDoc = evt.target.ownerDocument;
var g = svgRoot,
p,
targetX,
targetY,
stateTarget = evt.target;
if (state === PAN || state === DRAG) {
// Quit pan mode
state = NONE;
if (stateTarget.getCTM() !== null && enableSnap){
// Snap object
p = getEventPoint(evt).matrixTransform(g.getCTM().inverse());
targetX = (stateTarget.getCTM().e - g.getCTM().e) / g.getCTM().a;
targetY = (stateTarget.getCTM().f - g.getCTM().f) / g.getCTM().a;
setCTM(stateTarget, root.createSVGMatrix().translate(snap(targetX, gridSize), snap(targetY, gridSize)).multiply(g.getCTM().inverse()).multiply(stateTarget.getCTM()));
stateOrigin = p;
}
}
};
/**
* Register handlers
*/
// MODIFICATION: registers events through jQuery
$root.bind('mouseup', handleMouseUp)
.bind('mousedown', handleMouseDown)
.bind('mouseenter', handleMouseEnter)
.bind('mouseleave', handleMouseLeave);
//if (navigator.userAgent.toLowerCase().indexOf('webkit') >= 0) {
window.addEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari/others
window.addEventListener('DOMMouseScroll', handleMouseWheel, false); // Firefox
};
/**
Enable SVG panning on an SVG element.
@param viewportId the ID of an element to use as viewport for pan. Required.
@param enablePan Boolean enable or disable panning (default enabled)
@param enableZoom Boolean enable or disable zooming (default enabled)
@param enableDrag Boolean enable or disable dragging (default disabled)
@param zoomScale Float zoom sensitivity, defaults to .2
**/
$.fn.svgPan = function (viewportId, enablePan, enableZoom, enableDrag, zoomScale, enableSnap, gridSize) {
enablePan = typeof enablePan !== 'undefined' ? enablePan : false;
enableZoom = typeof enableZoom !== 'undefined' ? enableZoom : true;
enableDrag = typeof enableDrag !== 'undefined' ? enableDrag : true;
zoomScale = typeof zoomScale !== 'undefined' ? zoomScale : 0.2;
enableSnap = typeof enableSnap !== 'undefined' ? enableSnap : true;
gridSize = typeof gridSize !== 'undefined' ? gridSize : 70;
return $.each(this, function (i, el) {
var $el = $(el),
svg,
viewport;
// only call upon elements that are SVGs and haven't already been initialized.
if ($el.is('svg') && $el.data('SVGPan') !== true) {
viewport = $el.find('#' + viewportId)[0];
if (viewport) {
init($el[0], viewport, enablePan, enableZoom, enableDrag, zoomScale, enableSnap, gridSize);
} else {
throw "Could not find viewport with id #" + viewportId;
}
}
});
};
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment