簡體   English   中英

如何從給定步長的 D3 SVG 貝塞爾曲線中獲取點?

[英]How to get points from a D3 SVG bezier curve with given step size?

所以我有一個像這樣的 D3 SVG 貝塞爾曲線: 在此處輸入圖片說明

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

在此處輸入圖片說明

因此,要獲得具有相等步長的坐標對數組。 如果可能,不要重新計算貝塞爾曲線。 如何在 D3js 中做這樣的事情?

借助這里的二分函數,您可能想要這樣的東西:

 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 個數據點) .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM