gpt4 book ai didi

javascript - 如何动态添加另一行?

转载 作者:行者123 更新时间:2023-12-03 08:40:18 24 4
gpt4 key购买 nike

我正在尝试创建在页面上随机移动的动态线,我还想通过鼠标移动来移动线的尖端,因此我尝试在“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

希望这有帮助!

关于javascript - 如何动态添加另一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33055018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com