how assign id attribute each append of circle can later use circles based on id. able clone circle on drag out id.
demo: https://jsbin.com/zuxetokigi/1/edit?html,output
code:
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp page</title> </head> <body> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script> <script> svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500); circle1 = svg.append("circle") .attr("id", "circletoclone") .attr("cx", 100) .attr("cy", 100) .attr("r", 20); var drag = d3.behavior.drag() .origin(function () { var t = d3.select(this); return {x: t.attr("cx"), y: t.attr("cy")}; }) .on('dragend', function (d) { var mousecoordinates = d3.mouse(this); if (mousecoordinates[0] > 120) { //append new element var circle2 = d3.select("svg").append("circle") .classed("drg", true) .attr("cx", 100) .attr("cy", 100) .attr("r", 20) .attr("cx", mousecoordinates[0]) .attr("cy", mousecoordinates[1]) .style("fill", "green"); } }); circle1.call(drag); </script> </body> </html>
i not sure why want that, if want give every circle unique id, use function generate guid/uuid ('globally unique identifier') every circle.
you add following function salvik meltser's guid/uuid function code (anywhere before drag function):
function guid() { function _p8(s) { var p = (math.random().tostring(16)+"000000000").substr(2,8); return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ; } return _p8() + _p8(true) + _p8(true) + _p8(); } and then, append new circle, use .attr("id", guid()) generate new id circle.
var circle2 = d3.select("svg").append("circle") .attr("id", guid()) .classed("drg", true) ...
Comments
Post a Comment