1

The following toy code (jsfiddle here) write to the console log translate(20,0) translate(20,0) translate(20,0) translate(20,0) translate(20,0). Is it possible to get translate(100,0) as a "consolidated" translation?

var svg = d3.select('svg');

var rec=svg.append("rect")
    .attr("width",20)
    .attr("height", 20)
    .attr("x", 0)
    .attr("y", 20)
    .attr("fill","#00ffff")
    .attr("transform","")
    ;
   for (var i=0;i<10;i++) {
   rec
   .attr("transform",rec.attr("transform")+" translate(20,0)")
   ;
   }
   console.log(rec.attr("transform"))
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
tic
  • 4,009
  • 15
  • 45
  • 86
  • 1
    Um, `20 * 5`? `rec.attr("transform",rec.attr("transform")+" translate(" + (20 * 5) + ",0)");`? – Mark Sep 06 '18 at 15:34

1 Answers1

1

First of all, I believe you want to get translate(200,0) as the result, not translate(100,0), since there are 10 loops.

That being said, you have to get the translate values and add 20 to the first one and 0 to the second one. Otherwise you'll just concatenate strings, as you are doing right now.

Unfortunately there is no native method in D3 v4/v5 to get the transform value, so I'll use the function provided in this answer, with a slight modification (the if conditional), since your first value is an empty string (""):

function getTranslation(transform) {
  if (transform === "") {
    return [0, 0]
  };
  var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
  g.setAttributeNS(null, "transform", transform);
  var matrix = g.transform.baseVal.consolidate().matrix;
  return [matrix.e, matrix.f];
}

So, all you need is to get the current translate and add the value you want in your for loop:

for (var i = 0; i < 10; i++) {
  var currentTransform = getTranslation(rec.attr("transform"));
  rec.attr("transform", "translate(" + (currentTransform[0] + 20) + ",0)");
}

Here is the demo:

var svg = d3.select('svg');

var rec = svg.append("rect")
  .attr("width", 20)
  .attr("height", 20)
  .attr("x", 0)
  .attr("y", 20)
  .attr("fill", "#00ffff")
  .attr("transform", "");

for (var i = 0; i < 10; i++) {
  var currentTransform = getTranslation(rec.attr("transform"));
  rec.attr("transform", "translate(" + (currentTransform[0] + 20) + ",0)");
}

console.log(rec.attr("transform"))

function getTranslation(transform) {
  if (transform === "") {
    return [0, 0]
  };
  var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
  g.setAttributeNS(null, "transform", transform);
  var matrix = g.transform.baseVal.consolidate().matrix;
  return [matrix.e, matrix.f];
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171