所以我有一個
我想從 D3 路徑中獲取具有給定步驟的點的 X、Y 坐標,如下所示:

因此,要獲得具有相等步長的坐標對陣列。如果可能,不要重新計算貝塞爾曲線。如何在 D3js 中做這樣的事情?
uj5u.com熱心網友回復:
借助這里的二分函式,您可能想要這樣的東西:
const
svg = d3.select("svg"),
width = 512,
height = 200;
const data = [];
const curve = "curveBasis";
var walk = function() {
for (let i = 0, v = 2; i < 50; i) {
v = Math.random() - 0.5;
v = Math.max(Math.min(v, 4), 0);
data.push({step: i, value: v});
}
}
walk();
walkX = d3.scaleLinear()
.domain([0, 49])
.range([10, width - 10]);
walkY = d3.scaleLinear()
.domain([0, 4])
.range([200 - 10, 10]);
const line = d3.line()
.curve(d3[curve])
.x(d => walkX(d.step))
.y(d => walkY(d.value));
svg
.append("path")
.attr("id", "svgpath")
.attr("d", line(data))
.attr("fill", "none")
.attr("stroke", "black");
var svgpath = document.getElementById("svgpath");
var findYatXbyBisection = function(x, path, error){
var length_end = path.getTotalLength(),
length_start = 0,
point = path.getPointAtLength((length_end length_start) / 2), // get the middle point
bisection_iterations_max = 50,
bisection_iterations = 0;
error = error || 0.01;
while (x < point.x - error || x > point.x error) {
// get the middle point
point = path.getPointAtLength((length_end length_start) / 2);
if (x < point.x) {
length_end = (length_start length_end)/2;
} else {
length_start = (length_start length_end)/2;
}
// Increase iteration
if (bisection_iterations_max < bisection_iterations)
break;
}
return point.y
}
for (let i = 0; i < data.length; i) {
console.log(findYatXbyBisection(walkX(i), svgpath, 0.01).toFixed(4));
}
<html>
<head>
<meta charset="utf-8" />
<title>SVG Line</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.1.1/d3.min.js" integrity="sha512-COTaPOlz12cG4fSfcBsxZsjauBAyldqp 8FQUM/dZHm ts/jR4AFoJhCqxy8K10Jrf3pojfsbq7fAPTb1XaVkg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<svg id="chart" width="512" height="200">
</svg>
請注意,回傳的 Y 值是 SVG 坐標,因此它們從頁面頂部的 0 開始。檢查 walkY 函式中使用的 range 函式,以重繪 您必須如何反轉 D3.js 中典型折線圖和條形圖的值。
當然,不是登錄到控制臺,您可以將值推送到自定義陣列并使用不同的間隔值,例如總行(路徑)寬度的 1/n 而不是我使用的 1/50(用于 50 個資料點) .
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323290.html
標籤:javascript svg d3.js
上一篇:無法在SVG中使文本加粗
