Skip to content Skip to sidebar Skip to footer

How To Transform (rotate) Svg Text Element Without Changing Coordinates?

I'm new to this d3.js. Here I'm trying to draw a bar chart using the d3.v3.js library. Here I'm facing few problems. I have tried to include measure labels onto the y-axis. But onc

Solution 1:

What you see right now is the expected result, because the rotate function of the transform attribute rotates the element around the origin (0,0), not around its center.

The easiest solution is dropping your attr("x") and attr("y") and positioning the text using the same transform:

var width = 300,
  height = 300;
var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);
var text = svg.append("text")
  .text("Sum (sales), Sum (quantity)")
  .attr("text-anchor", "middle")
  .attr("transform", "translate(20," + (height / 2) + ") rotate(-90)")
svg {
  border: 1px solid gray;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

Another solution is setting the center of the rotate to the same x and y values:

var width = 300,
  height = 300;
var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);
var text = svg.append("text")
  .text("Sum (sales), Sum (quantity)")
  .attr("text-anchor", "middle")
  .attr("x", 20)
  .attr("y", 150)
  .attr("transform", "rotate(-90, 20, 150)")
svg {
  border: 1px solid gray;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

Solution 2:

I think you are looking for the css property transform-origin https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin


Post a Comment for "How To Transform (rotate) Svg Text Element Without Changing Coordinates?"