d3 polygon - drag and resize

by Serhii Matrunchyk

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>D3 Drawing</title>
  <script src="https://cdn.jsdelivr.net/d3js/3.5.9/d3.min.js"></script>
</head>
<body>
  <h3>Draw a polygon :D</h3>

CSS

svg {
    border: 1px solid;
}
path{
    fill: lightsalmon;
    stroke: salmon;    
    stroke-width: 5px;
}

JavaScript

let dragging = false;
let drawing = false;
let startPoint = [];

/* const rect = document.body;
rect.height -= 15;
const margin = { top: 25, right: 0, bottom: 55, left: 65 };
const width = rect.width - margin.left - margin.right;
const height = rect.height - margin.top - margin.bottom; */

const svg = d3.select('body').append('svg')
    .attr('height', 1000)
    .attr('width', 1000);

const points = [];
let g;

// behaviors
const dragger = d3.behavior.drag()
    .on('drag', handleDrag)
    .on('dragend', function(d){
        dragging = false;
    });
    
svg.on('mouseup', function (event) {
		console.log(event);
    
    if (dragging) return;
    
    drawing = true;
    startPoint = [event.clientX, event.clientY];
    console.log(startPoint);
    
    if (svg.select('g.drawPoly').empty()) {
    	g = svg.append('g').attr('class', 'drawPoly');
    }
    
    if (event.currentTarget.hasAttribute('is-handle')) {
        closePolygon();
        return;
    }
    
    points.push(dstartPoint);
    console.log(points)
    g.select('polyline').remove();
    const polyline = g.append('polyline').attr('points', points)
                    .style('fill', 'none')
                    .attr('stroke', '#000');
        g.selectAll('circle')
        .data(points)
        .enter()
        .append('circle')
        .attr('cx', points[i][0])
        .attr('cy', points[i][1])
        .attr('r', 4)
        .attr('fill', 'yellow')
        .attr('stroke', '#000')
        .attr('is-handle', 'true')
        .style({cursor: 'pointer'});
});
function closePolygon() {
    svg.select('g.drawPoly').remove();
    var g = svg.append('g');
    g.append('polygon')
    .attr('points', points)
    .style('fill', getRandomColor());
    for(var i = 0; i < points.length; i++) {
        var circle = g.selectAll('circles')
        .data([points[i]])
        .enter()
        .append('circle')
        .attr('cx', points[i][0])
        .attr('cy', points[i][1])
        .attr('r', 4)
        .attr('fill',...