var w = 280, h = 280; var svg = d3.select("#d3").append("svg") .attr("width", w) .attr("height", h); var lines = [ [{x:0 , y: 0}, {x: 250, y: 250}], [{x:0, y: 250}, {x: 250, y: 0}], [{x:0 , y: 0}, {x: 0, y: 250}], [{x:0, y: 250}, {x: 250, y: 250}], [{x:250 , y: 250}, {x: 250, y: 0}], [{x:250, y: 0}, {x: 0, y: 0}] ]; //define colors for the lines var lines_colors = [ {"color" : "green"}, {"color" : "purple"}, {"color" : "black"}, {"color" : "black"}, {"color" : "black"}, {"color" : "black"} ]; var line = d3.svg.line() .x(function(d) { return d.x; }) .y(function(d) { return d.y; }) .interpolate("basis"); svg.selectAll(".line") .data(lines) .enter().append("path") .attr("class", "line") .style("stroke", function(d,i) { return lines_colors[i].color; }) .attr("d", line); var drag = d3.behavior.drag() .origin(Object) .on("drag", function(){ dragmove(this); }); function dragmove(dragged) { var x = d3.select(dragged).attr("cx"); var y = d3.select(dragged).attr("cy"); d3.select(dragged) .attr("cx", Math.min(w,+x + d3.event.dx)) .attr("cy", Math.min(h,+y + d3.event.dy)); } function generateit(){ var circles = svg.selectAll("circle"); var json_circles = JSON.stringify(circles.data()); d3.select("#console").html('var jsonCircles = '+json_circles+';'); } d3.select("#exportit").on("click", generateit); var jsonCircles = [ { "x": 0, "y": 0, "radius": 10, "color" : "green" }, { "x": 50, "y": 50, "radius": 10, "color" : "green"}, { "x": 100, "y": 100, "radius": 10, "color" : "green" }, { "x": 150, "y": 150, "radius": 10, "color" : "green"}, { "x": 200, "y": 200, "radius": 10, "color" : "green" }, { "x": 250, "y": 250, "radius": 10, "color" : "green" }, { "x": 125, "y": 125, "radius": 10, "color" : "red" }, { "x": 0, "y": 250, "radius": 10, "color" : "purple" }, { "x": 50, "y": 200, "radius": 10, "color" : "purple" }, { "x": 100, "y": 150, "radius": 10, "color" : "purple" }, { "x": 150, "y": 100, "radius": 10, "color" : "purple" }, { "x": 200, "y": 50, "radius": 10, "color" : "purple" }, { "x": 250, "y": 0, "radius": 10, "color" : "purple" }]; var circles = svg.selectAll("circle") .data(jsonCircles) .enter() .append("circle"); var circleAttributes = circles .attr("cx", function (d) { return d.x; }) .attr("cy", function (d) { return d.y; }) .attr("r", function (d) { return d.radius; }) .style("fill", function(d) { return d.color; }) .call(drag); //drag magic - built in d3 behavior: https://github.com/mbostock/d3/wiki/Drag-Behavior#wiki-drag
<div id="exportit">Export</div> <div id="d3"></div> <div id="console"></div>
#d3 svg{ margin:30px; padding:10px; } .line{ stroke-width: 3px; } #exportit { background:#000; cursor:pointer; color:#fff; width:45px; padding:2px 4px; }