D3 v4 tests1

by b_g_v

HTML

<script src="https://d3js.org/d3.v4.min.js"></script>
<div>
  <svg width="500" height="300"></svg>
</div>

JavaScript

var svg = d3.select("svg");
var width = +svg.attr("width");
var height = +svg.attr("height");

var circles = svg.selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", d => d.x)
    .attr("cy", d => d.y)
    .attr("r", 20)
    .style("fill", "steelblue")
    .call(d3.drag()
        .on("start", function(event, d) {
            d3.select(this).raise().classed("active", true);
        })
        .on("drag", function(event, d) {
            // Adjust coordinates within the SVG boundaries
            d.x = Math.max(0, Math.min(width, event.x));
            d.y = Math.max(0, Math.min(height, event.y));

            d3.select(this).attr("cx", d.x).attr("cy", d.y);
        })
        .on("end", function(event, d) {
            d3.select(this).classed("active", false);
            d.fixed = true; // Marks the node as fixed
        })
    );