d3 polygon - drag and resize
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Draw</title>
<script src="https://cdn.jsdelivr.net/d3js/3.5.9/d3.min.js"></script>
</head>
<body></body>
CSS
svg {
border: 1px solid;
}
path{
fill: lightsalmon;
stroke: salmon;
stroke-width: 5px;
}
JavaScript
var dragging = false, drawing = false, startPoint;
var width = 960,
height = 500,
resolution = 20,
r = 15;
var svg = d3.select('body').append('svg')
.attr('height', height)
.attr('width', width);
var points = [], g;
var spos = [];
// behaviors
var dragger = d3.behavior.drag()
.on('drag', handleDrag)
.on('dragend', function(d){
dragging = false;
});
function round(p, n) {
return p % n < n / 2 ? p - (p % n) : p + n - (p % n);
}
function gridpos(x,y,points){
if(points.length < 1){
return [round(Math.max(r, Math.min(width - r, d3.mouse(this)[0])), resolution),
round(Math.max(r, Math.min(width - r, d3.mouse(this)[1])), resolution)];
}else{
if(Math.abs(d3.mouse(this)[0] - points[points.length - 1][0]) > Math.abs(d3.mouse(this)[1] - points[points.length - 1][1])){
return [round(Math.max(r, Math.min(width - r, d3.mouse(this)[0])), resolution),
points[points.length - 1][1]];
}else{
return [points[points.length - 1][0],
round(Math.max(r, Math.min(width - r, d3.mouse(this)[1])), resolution)];
}
}
}
svg.selectAll('.vertical')
.data(d3.range(1, width / resolution))
.enter().append('line')
.attr('class', 'vertical')
.attr('x1', function(d) { return d * resolution; })
.attr('y1', 0)
.attr('x2', function(d) { return d * resolution; })
.attr('y2', height)
.attr('stroke', '#53DBF3')
.attr('stroke-width', 1)
.attr('shape-rendering', 'crispEdges');
svg.selectAll('.horizontal')
.data(d3.range(1, height / resolution))
.enter().append('line')
.attr('class', 'horizontal')
.attr('x1', 0)
.attr('y1', function(d) { return d * resolution; })
.attr('x2', width)
.attr('y2', function(d) { return d * resolution; })
.attr('stroke', '#53DBF3')
.attr('stroke-width', 1)
.attr('shape-rendering', 'crispEdges');
svg.on('mouseup',...