How can I click to add or drag in D3?
http://stackoverflow.com/questions/19911514/how-can-i-click-to-add-or-drag-in-d3
by p b
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<body></body>
CSS
dot{
fill:lightblue;
stroke:#999999;
}
JavaScript
function click(){
// Ignore the click event if it was suppressed
if (d3.event.defaultPrevented) return;
// Extract the click location\
var point = d3.mouse(this)
, p = {x: point[0], y: point[1] };
// Append a new point
svg.append("circle")
.attr("transform", "translate(" + p.x + "," + p.y + ")")
.attr("r", "5")
.attr("class", "dot")
.style("cursor", "pointer")
.call(drag);
}
// Create the SVG
var svg = d3.select("body").append("svg")
.attr("width", 700)
.attr("height", 400)
.on("click", click);
// Add a background
svg.append("rect")
.attr("width", 700)
.attr("height", 400)
.style("stroke", "#999999")
.style("fill", "#F6F6F6")
var box = svg.append('rect')
.attr("width", 50)
.attr("height", 50)
.attr("x", 100)
.attr("y", 100)
.attr("fill", "red")
.on("mouseover", function(){
console.log("box rollover")
});
var endLine = svg.append('rect')
.attr("width", 200)
.attr("height", 400)
.attr("x", 200)
.attr("fill", "steelblue")
.on("mouseover", function(){
console.log("box rollover")
});
/// Define drag beavior
var drag = d3.behavior.drag()
.on("drag", dragmove);
function dragmove(d) {
// if the event.x goes over a boundry, trigger "dragend"
if(d3.event.x > 200){
//drag.dragend();
drag.trigger("dragend");
}
var x = d3.event.x;
var y = d3.event.y;
d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}