Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a shape in d3.js by drag and drop of a DOM element

I am trying to create a simple shape, let's say a circle, in d3.js using drag and drop of a DOM element, let's say a div. So here is what I did:

<!DOCTYPE html>
<html>
<head>
  <title>d3 tree with drag and drop</title>
  <style type="text/css">
   #dropInSVG {
     width:200px;
     height:200px; 
     margin-left:20px;
     background-color:#F8F8F8 ;
  }

#dropInSVG svg {
    width: 200px;
    height:200px;
    background-color:yellow;
 } 

#tobeDropped{
width:50px; 
height:15px;
background-color:pink;
float:left; 
}

#mainContainer {
width: 250px;
height: 250px;
background-color:orange;
cursor:pointer;
}

</style>
</head>
<body>
<div id="mainContainer">
<div id="dropInSVG"></div>
<div id="tobeDropped"></div>
</div>
</body>
<script type="text/javascript" src="./lib/jquery.js"></script>
<script type="text/javascript" src="./lib/jquery-ui.js"></script>
<script type="text/javascript" src="./lib/d3.js"></script>
<script type="text/javascript" src="./lib/d3.layout.js"></script>
<script type="text/javascript" src="d3appDrag.js"></script>
</html>

JavaScript code:

  var treeCreator = function(){}; 


  treeCreator.prototype.callbacktest = function(svgContainer){
  alert('the element has been dropped');
  }; 

  treeCreator.prototype.createTreeNode = function(theSVG){
  $('#tobeDropped').remove();
  theSVG.append("circle")
    .style("stroke","green")
    .style("fill","white")
    .attr("r",40)
    .attr("cx", 100)
    .attr("cy", 100)
    .on("mouseover", function () {
        d3.select(this).style("fill", "aliceblue");
    })
        .on("mouseout", function () {
        d3.select(this).style("fill", "red");
    }); 
 }; 

 $(document).ready(function(){

    $('#tobeDropped').draggable({containment:'#mainContainer'});

var theSVG = d3.select('#dropInSVG')
.append("svg")
.attr("width",200)
.attr("height",200);

var tc = new treeCreator(); 

$('#dropInSVG').droppable({
    drop: function(){
        tc.createTreeNode(theSVG); 
    }
});

  });

The problem is that the circle is not showing up. Could you please see what's wrong?

Thanks Mohamed Ali

like image 827
Mohamed Ali JAMAOUI Avatar asked Nov 30 '25 21:11

Mohamed Ali JAMAOUI


1 Answers

I resolved this issue by using

.append("svg:svg") 
 and 
.append("svg:circle")

instead of

.append("svg")
 and
.append("circle"); 

however I don't know why I should do that, for instance the following example works with the first type of selectors in jsFiddle however it didn't work when I tried locally in my browser!

like image 112
Mohamed Ali JAMAOUI Avatar answered Dec 02 '25 10:12

Mohamed Ali JAMAOUI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!