Reputation: 239
I am very new to d3.js need some help. I am trying to draw a line between 2 points. My problem here is everything should be dynamic, i.e. we usually follow a rule of telling x1
, x2
, y1
and y3
positions. Here's an example
var canvas = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var line = canvas.append("line")
.attr("x1", 0) // x1 position
.attr("y1", 100) // y1 position
.attr("x2", 400) // x2 position
.attr("y2", 400) // y2 position
.attr("stroke", "green")
.attr("stroke-width", 10);
I want those positions to be created dynamically, i.e. when I click on the webpage a point should be created and drag it from the position and place it in some other position. How can I do this?
Thank you
Upvotes: 1
Views: 878
Reputation: 50
A line is a simple line between two points and is described by four required attributes.
x1: The x position of the first end of the line as measured from the left of the screen.
y1: The y position of the first end of the line as measured from the top of the screen.
x2: The x position of the second end of the line as measured from the left of the screen.
y2: The y position of the second end of the line as measured from the top of the screen.
The following is an example of the code section required to draw a line;
holder.append("line") // attach a line
.style("stroke", "black") // colour the line
.attr("x1", 100) // x position of the first end of the line
.attr("y1", 50) // y position of the first end of the line
.attr("x2", 300) // x position of the second end of the line
.attr("y2", 150); // y position of the second end of the line
This will produce a line as follows;
enter image description here
The line extends from the point 100,50 to 300,150 (x1,y1 to x2,y2).
For more details refer
Upvotes: 1
Reputation: 32327
So first you will need to append your line to the svg just as you are doing Snippet below:
var mySVG = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
var line = mySVG.append("line")
.attr("class", ".line")//note: added a class to select later for dynamically updating.
.attr("x1", 0) // x1 position
.attr("y1", 100) // y1 position
.attr("x2", 400) // x2 position
.attr("y2", 400) // y2 position
.attr("stroke", "green")
.attr("stroke-width", 10);
In your drag end callback you can update the line using select as below.
mySVG.select(".line")
.attr("x1", 200) // x1 new position
.attr("y1", 300) // y1 new position
.attr("x2", 400) // x2 new position
.attr("y2", 400) // y2 new position
.attr("stroke", "green")
.attr("stroke-width", 10);
hope this helps!
Upvotes: 0