Skip to content

Instantly share code, notes, and snippets.

@pixelpusher
Forked from anonymous/jsbin.akoCAkA.css
Last active August 29, 2015 14:01
Show Gist options
  • Save pixelpusher/598680ad43bec694c2aa to your computer and use it in GitHub Desktop.
Save pixelpusher/598680ad43bec694c2aa to your computer and use it in GitHub Desktop.
#svg {
width:400px;
height:400px;
background-color: #999;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script src="http://snapsvg.io/assets/js/snap.svg-min.js"></script>
<script src="http://snapsvg.io/assets/js/prism.js"></script>
</head>
<body>
<svg id="svg"></svg>
</body>
</html>
//
// Demonstrates adding SVG shapes to a group and using a mouse drag event to transform them
//
// Not a great example due to needing to
// create extra variables on the group (newtx and tx, etc.)
//
// by Evan Raskob
//
window.addEventListener('load', function() {
var s = Snap('#svg'); // this attaches SnapSVG to our SVG section of the page
// create a circle
var bigCircle = s.circle(100, 100, 75);
// create some text
var t = s.text(75,100,"drag me").attr({fill:'white'});
// create group of circle and text so they drag together
var circleGroup = s.group(bigCircle, t);
circleGroup.tx = 0; // current x translation
circleGroup.ty = 0; // current y translation
// create a small, clickable circle
var smallCircle = s.circle(40,40,30);
smallCircle.attr({fill:'purple'});
smallCircle.click(function() {
// hide on click
console.log('click');
this.animate({opacity:0},1000);
});
// function to change the group's position while moving (dragging)
//
var moveFunc = function (dx, dy, posx, posy) {
//this string represents the transform
var tstring = 't'+(this.tx+dx)+','+(this.ty+dy);
// keep track of new translations to apply when mouse released
this.newtx = this.tx+dx;
this.newty = this.ty+dy;
//console.log(tstring);
// apply the transform to this SVG group
circleGroup.transform(tstring);
};
// function to run when dragging starts
var startDragFunc = function(posx, posy, e){
this.attr({fill:'red'});
console.log("Move started:" + posx + " " + posy);
};
// function to run when dragging is finished
var stopDragFunc = function(e){
console.log("Move stopped");
this.attr({fill:'black'});
// update translated position
this.tx = this.newtx;
this.ty = this.newty;
};
// attach the drag functions to the circle and text group
circleGroup.drag(moveFunc,
startDragFunc,
stopDragFunc);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment