Last active
August 29, 2015 14:04
-
-
Save jakosz/51881a4beac78f015dbe to your computer and use it in GitHub Desktop.
Drag and drop SVG elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<meta charset='utf-8'> | |
<style> | |
body { | |
background: rgb(200,200,200); | |
} | |
svg { | |
margin: auto; | |
display: block; | |
background: white; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://szejda.pl/code/helpers.js"></script> | |
<script> | |
var mainw = 960, | |
mainh = 500; | |
d3.select('body').append('svg') | |
.attr('width', mainw) | |
.attr('height', mainh); | |
d3.select('svg').selectAll('tmp') | |
.data([1, 2, 3]).enter() | |
.append('g') | |
.attr('transform', 'translate(0,0)') | |
.append('rect') | |
.attr('width', '50px') | |
.attr('height', '50px') | |
.attr('x', function(d){ return d * 55; }) | |
.attr('y', 100) | |
.attr('fill', function(d, i){ return ['red', 'green', 'blue'][i]; }); | |
function draggable(){ | |
// Global draggables dict | |
if (!('dd' in window)) { | |
window.dd = {}; | |
} | |
var id = 'dd-' + h.randomString(); | |
// "Register" the new draggable element: | |
dd[id] = { | |
'on': false, | |
'tx': 0, | |
'ty': 0, | |
'x0': null, | |
'x1': null, | |
'y0': null, | |
'y1': null | |
} | |
var selection = this instanceof d3.selection ? this : d3.select(this); | |
selection | |
.on('mousedown', function(){ | |
console.log(id); | |
dd[id].on = true; | |
dd[id].x0 = d3.event.clientX; | |
dd[id].y0 = d3.event.clientY; | |
}) | |
.on('mouseup', function(){ dd[id].on = false; }) | |
.on('mousemove', function() { | |
if (dd[id].on) { | |
if (dd[id].x1 != null) { | |
dd[id].x0 = dd[id].x1; | |
dd[id].y0 = dd[id].y1; | |
} | |
dd[id].x1 = d3.event.clientX; | |
dd[id].y1 = d3.event.clientY; | |
dd[id].tx = dd[id].tx + (dd[id].x1 - dd[id].x0); | |
dd[id].ty = dd[id].ty + (dd[id].y1 - dd[id].y0); | |
d3.select(this) | |
.attr('transform', 'translate(' + dd[id].tx + ',' + dd[id].ty + ')'); | |
}; | |
}); | |
} | |
d3.selectAll('g').each(draggable); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment