d3 - circle
draw a circle on mousedown
by Amanda Williamson
CSS
svg {
border: solid 1px blue;
}
circle {
fill: lightgreen;
stroke: green;
stroke-width: 2px;
}
JavaScript
function getRadius(x1, y1, x2, y2) {
return Math.sqrt((Math.pow(x2 - x1, 2) + (Math.pow(y2 - y1, 2))));
}
var w = 600, h = 500, circle, circleData = [ ], isDown = false, m1, m2, isDrag = false;
var svg = d3.select("body").append('svg').attr('width', w).attr('height', h)
.on('mousedown', mousedown)
.on('mousemove', mousemove);
var dragC = d3.behavior.drag().on('drag', dragCircle);
function dragCircle() {
console.log('dragCircle');
var e = d3.event;
circleData.forEach(function(datum, index){
datum.cx += e.dx;
datum.cy += e.dy;
});
updateCircle();
}
/*var dragP = d3.behavior.drag().on('drag', dragPoint);
function dragPoint() {
console.log('dragPoint');
var e = d3.event;
d3.select(this).attr('cx', function(d) { return d.cx += e.dx })
.attr('cy', function(d) { return d.cy += e.dy });
updateCircle();
}*/
function drawCircle() {
console.log('drawCircle');
circle = svg.append('circle');
}
function updateCircle() {
console.log('updateCircle');
circle.attr({
cx: circleData.cx,
cy: circleData.cy
});
var resize = svg.selectAll('rect').data(circleData);
resize.enter()
.append('rect')
.attr('width', 5)
.attr('height', 5);
resize.attr('x', function (d) { return d.x })
.attr('y', function (d) { return d.y });
}
function mousedown() {
m1 = d3.mouse(this);
if (!isDown && !circle) {
console.log('if');
drawCircle();
circleData = { cx: m1[0], cy: m1[1] };
updateCircle();
isDrag = false;
} else {
console.log('else');
circle.call(dragC);
//d3.selectAll('rect').call(dragP);
isDrag = true;
}
isDown = !isDown;
}
function mousemove() {
m2 = d3.mouse(this);
if(circle && isDown && !isDrag) {
updateCircle();
circle.attr("r", getRadius(m1[0], m1[1],...