svg-pan-zoom
Version:
JavaScript library for panning and zooming an SVG image from the mouse, touches and programmatically.
73 lines (63 loc) • 2.52 kB
HTML
<html>
<head>
<script src="../dist/svg-pan-zoom.js"></script>
</head>
<body>
<h1>Demo for svg-pan-zoom: In-line SVG</h1>
<div id="container" style="width: 500px; height: 500px; border:1px solid black; ">
<svg id="svg-id" xmlns="http://www.w3.org/2000/svg" style="display: inline; width: inherit; min-width: inherit; max-width: inherit; height: inherit; min-height: inherit; max-height: inherit;" version="1.1">
<defs>
<linearGradient id="linear-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:rgb(56,121,217);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(138,192,7);stop-opacity:1" />
</linearGradient>
</defs>
<g fill="none">
<g stroke="#000" fill="#FFF">
<rect x="5" y="5" width="240" height="240" fill="url(#linear-gradient)"/>
<path d="M 5 5 L 245 245 Z"/>
</g>
</g>
</svg>
<button id="animate">Animate</button>
</div>
<script>
// Don't use window.onLoad like this in production, because it can only listen to one function.
window.onload = function() {
// Expose to window namespase for testing purposes
window.panZoomInstance = svgPanZoom('#svg-id', {
zoomEnabled: true,
controlIconsEnabled: true,
fit: true,
center: true,
minZoom: 0.1
});
// Zoom out
panZoomInstance.zoom(0.2);
function customPanBy(amount){ // {x: 1, y: 2}
var animationTime = 300 // ms
, animationStepTime = 15 // one frame per 30 ms
, animationSteps = animationTime / animationStepTime
, animationStep = 0
, intervalID = null
, stepX = amount.x / animationSteps
, stepY = amount.y / animationSteps
intervalID = setInterval(function(){
if (animationStep++ < animationSteps) {
panZoomInstance.panBy({x: stepX, y: stepY})
} else {
// Cancel interval
clearInterval(intervalID)
}
}, animationStepTime)
}
var button = document.getElementById("animate")
button.addEventListener("click", function() {
// Pan by any values from -80 to 80
customPanBy({x: Math.round(Math.random() * 160 - 80), y: Math.round(Math.random() * 160 - 80)})
});
};
</script>
</body>
</html>