Reputation: 257
I want to create a circle simultaneously by drawing the radius.
The following code draws the radius.
What do I need to add to the code, so that it creates the circle (with no fill etc. just the circumference with a black stroke) simultaneously as the radius is being defined ?
d3.select('body').append('svg');
function add(ink) {
var c, p, rf = false,
r = d3.svg.line().x(function(d) {
return d[0];
}).y(function(d) {
return d[1];
});
ink.on('mousedown', function() {
rf = true;
c = d3.mouse(this);
p = d3.select('svg').append('path').attr('d', r([c, c])).style({
'stroke': '#000'
});
}).on('mouseup', function() {
rf = false;
}).on('mousemove', function() {
if (rf) {
l = r([c, d3.mouse(this).map(function(x) {
return x - 1;
})]);
p.attr('d', l);
}
});
}
d3.select('svg').call(add);
<script src="https://d3js.org/d3.v3.min.js"></script>
Upvotes: 1
Views: 94
Reputation: 19319
I made a few updates to your code for the circle with radius of the current length of the line.
foo
mousedown
with radius of 1 (so it is not visible) - you can style with no fill
and black stroke
etcmousemove
handler, compute the distance between the origin and the current mouse point (less 1) and make that the radius of the circle.d3.select('body').append('svg');
function add(ink) {
var foo; // some variable for your circle
var c, p, rf = false,
r = d3.svg.line().x(function(d) {
return d[0];
}).y(function(d) {
return d[1];
});
ink.on('mousedown', function() {
rf = true;
c = d3.mouse(this);
p = d3.select('svg').append('path').attr('d', r([c, c])).style({
'stroke': '#000'
});
// create a circle with radius 1 on mousedown
foo = d3.select('svg').append('circle')
.attr('cx', c[0])
.attr('cy', c[1])
.attr('r', 1)
.attr('fill', 'none')
.attr('stroke', '#000');
}).on('mouseup', function() {
rf = false;
}).on('mousemove', function() {
if (rf) {
// pt0 is origin; pt1 is mouse location -1
var pt0 = c;
var pt1 = d3.mouse(this).map(function(x) {
return x - 1;
});
// your new line
l = r([pt0, pt1]);
p.attr('d', l);
// formula for distance between two points
var dx = Math.abs(pt1[0] - pt0[0]);
var dy = Math.abs(pt1[1] - pt0[1]);
var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
// set circle radius to distance between two points
foo.attr('r', d);
}
});
}
d3.select('svg').call(add);
<script src="https://d3js.org/d3.v3.min.js"></script>
Upvotes: 1