how do I add another line dynamically?

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

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);

回答1:

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!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!