使用d3从一侧到另一侧的水平淡入过渡?

tur*_*nip 3 javascript d3.js

我知道如何使用opacity属性在转换中进行正常淡入淡出,但是我将如何从元素的一端开始转换并逐渐水平完成?

像这样的东西:

在此输入图像描述

我试图为一些文本这样做:

text = svg.selectAll(".myText")
          .data(myData)
          .enter()
          .append("text")
          .attr("class", "myText")
          .attr("text-anchor", "start")
          .attr("fill-opacity", 0)
          .text(function (d)
          {
              return d.message
          });

text.transition()
    .delay(500)
    .duration(1000)
    .attr("fill-opacity", 1)
Run Code Online (Sandbox Code Playgroud)

Ste*_*ich 5

纯CSS答案

您可以在这里看到如何使用纯CSS执行此操作: CSS从左向右淡化

D3方法

以下是链接答案中给出的相同方法,仅将其应用于D3 ......

要点是在文本上放置一个框,并使用过渡来修改框宽(从完全覆盖文本到完全显示它).

  • 为防止框边缘可见且过于刺耳,应用渐变.

  • 为了确保框能够很好地覆盖文本,覆盖矩形使用函数从文本的边界框中使用参数 getBBox()

var height = 25,
    width = 100;

d3.select('div').append('svg')
        .attr('width', '100%')
        .attr('viewBox', "0 0 " + width + " " + height)
        .attr('style', 'border: solid 1px green')
        .append('g')
        .attr('transform','translate('+ width/2 +','+ height/2 +')')
        .attr('id', 'main');

var text = d3.select('#main').append('text')
             .attr('class', 'myText')
             .attr('text-anchor', 'middle')
             .attr('alignment-baseline','middle') 
             .text('My Message');

bbox = text[0][0].getBBox();

var gradient = d3.select('svg').append("defs")
  .append("linearGradient")
    .attr("id", "gradient")
    .attr("x1", "0%")
    .attr("x2", "0%")
    .attr("spreadMethod", "pad");

gradient.append("stop")
    .attr("offset", "0%")
    .attr("stop-color", "#fff")
    .attr("stop-opacity", 1);

gradient.append("stop")
    .attr("offset", "100%")
    .attr("stop-color", "#fff")
    .attr("stop-opacity", 0);

fadeBox = d3.select('#main').append('rect')
  .attr('x', bbox.x)
  .attr('y', bbox.y)
  .attr('width', bbox.width)
  .attr('height', bbox.height)
  .style("fill", "url(#gradient)");



fadeBox.transition()
  .delay(500)
  .duration(2000)
  .attr('width', 0)
  .attr('x', bbox.width)


gradient.transition()
  .delay('500')
  .duration('2000')
  .attr('x1','100%')
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<div>

</div>
Run Code Online (Sandbox Code Playgroud)