簡體   English   中英

d3 中的拖動位置

[英]Drag position in d3

const width = grid.clientWidth;
const height = grid.clientHeight;
svg.attr("width", width).attr("height", height);
const xValue = d => d.cx;
const yValue = d => d.cy;
const xScale = scaleLinear()
    .domain([-10, 10])
    .range([0 , width])
    .nice();

const yScale = scaleLinear()
    .domain([-10, 10])
    .range([height , 0 ])
    .nice();
svg
    .append("g")
    .attr("transform", `translate(${0},${yScale(0)})`)
    .call(axisBottom(xScale));

svg
    .append("g")
    .attr("transform", `translate(${xScale(0)},${0})`)
    .call(axisLeft(yScale));

function dragged(d) {
    console.log(event.x);
    select(this)
      .attr("cx", (d.x = event.x))
      .attr("cy", (d.y = event.y))
      .attr("transform", d => `translate(${xScale(xValue(d))},${yScale(yValue(d))})`);
  }
const pointG = svg.append("g");
  pointG
    .selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", d => xValue(d))
    .attr("cy", d => yValue(d))
    .attr("transform", `translate(${d => xScale(xValue(d))},${d => yScale(yValue(d))})`)
    .attr("r", radius).call(
      drag()
        .on("drag", dragged)
    );;
};
const data = [
  {
    cx: 9.0,
    cy: -9.38
  }
     {
       cx: 5.0,
       cy: 9.0
     }
];

基本上我想實現一個像 Desmos 坐標平面這樣的工具: https ://www.desmos.com/calculator/q8mwzeylbk。

我已經在 svg 的中心繪制了一個坐標平面,現在我在這個坐標平面上繪制了一些點。 問題是拖動后我會得到像素坐標而不是我想要的坐標。 如何根據坐標平面獲取拖動點的坐標? 我應該使用 scale.invert() 函數來轉換 SVG 坐標嗎?

您已經設置了比例函數,要獲取xy ,請在dragged()函數中使用它:

var planeX = xScale(xValue(d));
var planeY = yScale(yValue(d));

暫無
暫無

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

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