Skip to content

Instantly share code, notes, and snippets.

@feyderm
Last active March 4, 2017 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feyderm/4d143591b66725aed0f1855444752fd9 to your computer and use it in GitHub Desktop.
Save feyderm/4d143591b66725aed0f1855444752fd9 to your computer and use it in GitHub Desktop.
D3 v4 shape drag
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<!--viz-->
<div id="chart"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript">
var svg_dx = 800,
svg_dy = 400,
margin_x = 100;
var shapes = [ d3.symbolCircle,
d3.symbolCross,
d3.symbolDiamond,
d3.symbolSquare,
d3.symbolStar,
d3.symbolTriangle,
d3.symbolWye ];
var x = d3.scalePoint()
.domain(d3.range(0, shapes.length))
.range([margin_x, svg_dx - margin_x]);
var svg = d3.select("#chart")
.append("svg")
.attr("width", svg_dx)
.attr("height", svg_dy);
var symbol = d3.symbol().size([1500]),
color = d3.schemeCategory10;
var drag_behavior = d3.drag()
.on("start", dragstarted)
.on("drag", dragged);
svg.append("g")
.selectAll("path")
.data(shapes)
.enter()
.append("path")
.attr("d", symbol.type(shape => shape))
.attr("transform", (shape, i) => "translate(" + x(i) + ", -40)")
.style("fill", (shape, i) => color[i])
.call(drag_behavior)
.transition()
.duration((shape, i) => i * 800)
.attr("transform", (shape, i) => "translate(" + x(i) + "," + (svg_dy / 2) + ")");
function dragstarted() {
d3.select(this).raise();
}
function dragged(shape) {
var dx = d3.event.sourceEvent.offsetX,
dy = d3.event.sourceEvent.offsetY;
d3.select(this)
.attr("transform", shape => "translate(" + dx + "," + dy + ")");
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment