D3.js tests

by Haelle

HTML

<script src="https://d3js.org/d3.v5.min.js"></script>
<body>
  <!--
  <svg width="50" height="50">
    <circle cx="25" cy="25" r="25" fill="purple" />
  </svg>
  -->
</body>

CSS

svg {
  background-color: #FFF;
  cursor: default;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  border: 1px solid black;
}

svg:not(.active):not(.ctrl) {
  cursor: crosshair;
}

rect {border: 1px solid #00f;}

JavaScript

class DirectedGraphEditor {
	constructor() {
  	this.lastNodeId = -1
  	this.nodes = []
    this.colors = d3.scaleOrdinal(d3.schemeCategory10);
  	this.initSVG()
    }
    
  initSVG() {
  	this.svg = d3.select('body')
								 .append("svg")
                 .attr('width', 500)
                 .attr('height', 500)
                 .attr('oncontextmenu', 'return false;')
  }
  
  mousedown() {
  	var coords = d3.mouse(this.svg.node())
  	this.nodes.push({
    	'id': ++this.lastNodeId,
    	'x': coords[0],
      'y': coords[1],
      'r': 25
    })
    this.draw()
  }
  
  drawCircle(node) {
  	this.svg.append('circle')
	 					.attr('cx', node['x'])
   					.attr('cy', node['y'])
   					.attr('r',  node['r'])
            .style('fill', this.colors(node.id % 10))
  }
  
  draw() {
  	var self = this
  	this.nodes.forEach(function(node) {
    	self.drawCircle(node)
    })
    
    console.log(this.nodes)
  }
}

var dge = new DirectedGraphEditor()
dge.svg.on('click',() => dge.mousedown())