在svg中:translate vs position x和y

olu*_*man 24 javascript svg d3.js

当我要放置简单的物体,如rectline我应该使用transform属性或者xy属性?

// this
d3.selectAll('rect')
    .attr('x', Number)
    .attr('y', 0)

// or this?
d3.selectAll('rect')
    .attr("transform", function(d) { return 'translate(' + d + ', 0)' } );
Run Code Online (Sandbox Code Playgroud)

性能差异是什么?

met*_*ion 20

在SVG transform中不是硬件加速.对于单个元素,它们具有相同的性能(根据我的经验).但是,我使用transform更多来移动东西,因为在SVG中并非所有元素都有xy属性,请考虑......

<line x1="0" y1="0" x2="100" y2="100" />
<circle cx="100" cy="100" r="100" />
<path d="M 0 0 L 100 100" />
<rect x="0" y="0" width="100" height="100" />
Run Code Online (Sandbox Code Playgroud)

如果不使用,则必须为每个元素编写不同的实现transform.一个transform确实更快的区域是移动大量元素,如果你有......

<g transform="translate(100, 100)">
  <line x1="0" y1="0" x2="100" y2="100" />
  <circle cx="100" cy="100" r="100" />
  <path d="M 0 0 L 100 100" />
  <rect x="0" y="0" width="100" height="100" />
</g>
Run Code Online (Sandbox Code Playgroud)

与单独移动每个元素相比,处理密集程度更低