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 .
I have drawn a coordinate plane at the center of a svg, now I draw some points on this coordinate plane. 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?
You already have your scales functions set, to get the x
and y
, use this inside dragged()
function:
var planeX = xScale(xValue(d));
var planeY = yScale(yValue(d));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.