我正在尝试创建在页面上随机移动的动态行,我也想通过鼠标移动来移动行的尖端,因此我尝试在“ linedata”变量中添加另一个数据,但它仅呈现1行。

下面的代码在“ linedata”数组中只有1个数据,我尝试了类似

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

最佳答案

您可以创建一行并通过根据鼠标指针更改x1 / y1 / x2 / y2来移动该行。查看功能mousemove

有关生成随机行的信息,请参见函数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);


完整的工作代码here

希望这可以帮助!

10-01 04:25