简体   繁体   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
     }
];

Basically I want to implement a tool like Desmos coordinate plane: https://www.desmos.com/calculator/q8mwzeylbk .基本上我想实现一个像 Desmos 坐标平面这样的工具: https ://www.desmos.com/calculator/q8mwzeylbk。

I have drawn a coordinate plane at the center of a svg, now I draw some points on this coordinate plane.我已经在 svg 的中心绘制了一个坐标平面,现在我在这个坐标平面上绘制了一些点。 The problem is I will get the pixel coordinate after dragged not the coordinate I want.问题是拖动后我会得到像素坐标而不是我想要的坐标。 How do I get the coordinate of dragged point according to the coordinate plane?如何根据坐标平面获取拖动点的坐标? Should I use scale.invert() function to convert the SVG coordinates?我应该使用 scale.invert() 函数来转换 SVG 坐标吗?

You already have your scales functions set, to get the x and y , use this inside dragged() function:您已经设置了比例函数,要获取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