Search code examples
javascriptd3.jssvgangle

How to calcule the (x, y) positions based on angle in D3


The Idea is, when I rodate the triangle, the blue circle should be rotated too.

enter image description here

const data = { 
  '0x001': {x: 10000, y: 10000, a: 20 },
  '0x002': {x: 15000, y: 10000, a: 180 },
  '0x003': {x: 5000, y: 1000, a: 120 },
  '0x004': {x: 18000, y: 9000, a: 230 }
}

const domains = {
  x: [20000, 0], 
  y: [0, 20000]
}

const scales = {
  x: d3.scaleLinear().range([505, 0]).domain(domain.x);
  y: d3.scaleLinear().range([0,  620]).domain(domain.y);
}

var g = d3.select(el).selectAll('.d3-points');

// Create triangle object
const triangle = d3.symbol().type(d3.symbolTriangle).size(400);
var point = g.selectAll('.d3-point')
  .data(data, d => d.id + d.x + d.y + d.a)
  .enter().append("path")
  .attr("transform", (d) => `translate(${scales.x(d.x)}, ${scales.y(d.y)}) rotate(${d.a})`)
  .attr('class', 'd3-point').attr("d", triangle);

// Create circle object
g.selectAll('.d3-status')
   .data(data, d => d.id + d.x + d.y + d.a)
   .enter().append("circle")
   .attr("cx", d => {
     const x = scales.x(d.x)
     // return ((x * Math.cos(d.a)) + 23.459) // TRIED
     return x
   })
   .attr("cy", d => {
     const y = scales.y(d.y)
     // return (y * Math.sin(d.a)) + (50/2) // TRIED
     return y
   })
   .attr("r", 3)

Solution

  • You can create a <g> element to wrap around the point (triangle symbol), then append the circle to the <g> element instead of g, in that way your circle will rotate together with the triangle.