本文介绍了巩固D3中的连续翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下玩具代码()写入控制台日志 translate(20,0)translate(20,0)translate(20,0)translate(20,0)translate(20,0)
是否可以将 translate(100,0)作为合并翻译?

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


推荐答案

首先,我相信你想得到 translate(200,0)作为结果,而不是 translate(100,0),因为有10个循环。

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

话虽如此,你必须得到翻译值并添加 20 到第一个, 0 到第二个。否则你只是连接字符串,正如你现在所做的那样。

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.

不幸的是,D3 v4 / v5中没有原生方法来获取变换值,所以我' ll使用中提供的功能,稍作修改( if conditional),因为你的第一个值是一个空字符串():

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

以下是演示:

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>

这篇关于巩固D3中的连续翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 03:07