d3 path - drag and resize
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>drawRect</button>
CSS
svg {
border: 1px solid;
}
path{
stroke-width: 6;
stroke: blue;
}
JavaScript
$("button").click(function(){
var svg = d3.select("body").append("svg").attr({ width: 200, height: 200 }),
data = [],
lineFunction = d3.svg.line()
.x(function (data) {
return data.x;
})
.y(function (data) {
return data.y;
}),
path, isDown = false, count=0;
var dragP = d3.behavior.drag().on('drag', dragPath),
dragC = d3.behavior.drag().on('drag', dragCircle);
function dragPath(dataSource) {
var e = d3.event;
data.forEach(function(datum, index){
datum.x += e.dx;
datum.y += e.dy;
});
updatePath();
updateCircle();
}
function dragCircle(dataSource) {
console.log("dataSource", dataSource);
var e = d3.event;
console.log("e", e);
dataSource.x += e.dx;
dataSource.y += e.dy;
updateCircle();
updatePath();
}
function updatePath(){
if(!path){
path = svg.append('g').append('path');
}
path.attr('d', lineFunction(data));
}
function updateCircle(){
circle = svg.selectAll('circle').data(data);
circle.enter().append('circle').attr('r', 0).transition().duration(500).attr('r', 10);
circle.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; });
}
svg.on('mousedown', function(){
console.log("mousedown");
var m = d3.mouse(this);
console.log("n");
if(!count){
console.log("count");
if(!isDown){
console.log("down");
data[0] = { x: m[0], y: m[1] };
updatePath();
updateCircle();
} else {
console.log("d");
updateCircle();
d3.selectAll('circle').call(dragC);
path.call(dragP);
count++;
console.log(data);
}
}
isDown = !isDown;
})
.on('mousemove', function(){
console.log("move");
var m2 = d3.mouse(this);
if(path && count === 0){
if(isDown){
data[1] = { x: m2[0], y: m2[1] }; ...