旋转后如何获得新的X和Y位置?

时间:2019-06-29 09:54:15

标签: javascript d3.js

我需要制作一个Sunflowerplot,旋转线条之后,必须将它们的位置平移回去。但是我不知道旋转后如何获得新的x,y位置。

我只想旋转线条,但是其位置当然也会改变。

var xOld = (save[i][0])/(xS.value/100/3.4);
var yOld = (save[i][1])/(yS.value/100/3.5*-1); 

//Above code is to get and transform the position where to draw
//and works very well without rotate

var line = d3.select("svg")
        .append("line")
    .attr("stroke-width","1")
    //Backwardline
        .attr("x1",xOld-lineLength)
    .attr("y1",yOld)
        //I think that i need to translate the new position here
    .attr("transform", "translate(50, " + 360  +") rotate(" + 45 * -1+ ")")
    //Forwardline
    .attr("x2",(xOld)+lineLength)
    .attr("y2",(yOld))
    .style("stroke","blue");

1 个答案:

答案 0 :(得分:3)

我添加了一个代码段,您可以在其中确定花瓣的数量,并根据需要进行一些样式设置和旋转

const svg = d3.select('body').append('svg');

// The distance in pixels between the edge and the center of each petal
const petalRadius = 20;

// sin, cos, and tan work in radians
const fullCircle = 2 * Math.PI;

// Zero rads make the shape point to the right with the right angle
// Use - 0.5 * pi rads to make the first petal point upwards instead
// You can play with this offset to see what it does
const offset = - Math.PI / 2;

function drawSunflower(container, petals) {
  const radsPerPetal = fullCircle / petals;
  const path = container.append('path');

  // We're going to need this a lot. M moves to the given coordinates, in this case
  // That is the center of the sunflower
  const goToCenter = ` M ${petalRadius},${petalRadius}`;

  // Construct the `d` attribute. Start in the center and work form there.
  let d = goToCenter;
  let counter = 0;
  while (counter < petals) {
    const rads = counter * radsPerPetal + offset;
    const dx = Math.cos(rads) * petalRadius;
    const dy = Math.sin(rads) * petalRadius;

    // Draw a relative line to dx, dy, then go to center
    d += `l ${dx},${dy}` + goToCenter;
    counter += 1;
  }
  path.attr('d', d);
}

const transform = 2 * petalRadius + 5;
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 3; j++) {
    let container = svg.append('g').attr('transform', `translate(${i * transform}, ${j * transform})`);
    drawSunflower(container, i * 5 + j + 1);
  }
}
g > path {
  stroke: black;
  stroke-width: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>