Reputation: 598
I'm trying to create dynamic line that randomly moves on the page, I also want to move the tip of the line with mouse movement so I tried adding another data in "linedata" variable but it only renders 1 line.
the code below only has 1 data in "linedata" array, I tried something like
var random = {
a: Math.floor(Math.random()*randNum),
b: Math.floor(Math.random()*randNum),
};
linedata = [ "M 0 0 L 200 " + (100+random.a),
"M 100 100 L 200 " + (100+random.b) ];
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>d3 test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<script>
//Width and Height
var w = 500;
var h = 50;
//Create SVG Element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var line = svg.append("path")
.attr("stroke","orange")
.attr("stroke-width", 7)
.attr("fill","none");
//Global array
var linedata = [];
//random multiplier
var randNum = 50;
setInterval(function() {
var random = {
a: Math.floor(Math.random()*randNum),
};
linedata = [ "M 0 0 L 200 " + (100+random.a) ];
line.data(linedata);
line.attr("d", function(d) {
return d;
})
}, 10);
Upvotes: 0
Views: 70
Reputation: 32327
You can create a line and move the line by changing the x1/y1/x2/y2 as per the mouse pointer. See the function mousemove
For generating random lines see function generateLines
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
.on("mousemove", mousemove);
function generateLines() {
var line = svg.append("line")
.attr("stroke", "orange")
.attr("stroke-width", 7)
.attr("class", "line")
.attr("x1", generateRandomPoints())
.attr("y1", generateRandomPoints())
.attr("x2", generateRandomPoints())
.attr("y2", generateRandomPoints())
.attr("fill", "none");
}
function mousemove() {
var t = d3.mouse(this);
svg.selectAll(".line").attr("x1", t[0]).attr("y1", t[1]);
}
//make random points
function generateRandomPoints() {
return parseInt(Math.random() * 500);
}
//this will generate random lines after an interval of 3 secs
setInterval(function () {
generateLines();
}, 3000);
full working code here
Hope this helps!
Upvotes: 1