consolidate successive translations in D3

和自甴很熟 提交于 2020-01-15 12:26:14

问题


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"))

回答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>


来源:https://stackoverflow.com/questions/52207592/consolidate-successive-translations-in-d3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!