2

我正在为 d3.js 图创建一个特定的实现,似乎在动态创建 SVG 文档时,linearGradients 无法在 Webkit 浏览器上运行(仅在 Webkit 系列的 Chrome 上测试),而 Gecko 显示的是预期的行为。

我如何得出结论它与动态生成或d3有关?我尝试将生成的文档复制到一个空白页面中,渐变变得栩栩如生。

d3代码首先初始化文档:

// in construction:
// ...
svg = d3.select(el)
    .append('svg:svg')
    .attr('width', width)
    .attr('height', height),
defs = svg.append('svg:defs'),
linearGradient1 = defs.append('svg:linearGradient')
    .attr('id', 'linear-gradient-1')
    .attr('x1', 0)
    .attr('y1', 1)
    .attr('x2', 6.123233995736766e-17)
    .attr('y2', 0),
linearGradient1Stop1 = linearGradient1.append('svg:stop')
    .attr('offset', '0%')
    .attr('stop-color', '#e3e5e8'),
    // several other stops here ...

…而不是刷新渲染器,例如在将“节点”添加到图形数据结构之后,按需(注意:selfRef.node只是所有节点的 d3 选择器的句柄):

// called e.g. when adding new nodes:
refresh: function() {
    // ...
    // add new nodes
    var g = selfRef.node.enter().append('svg:g').attr('class', 'node');

    g.append('svg:rect')
        .attr('width', 144)
        .attr('height', 42)
        .attr('rx', 3)
        .attr('ry', 3)
        .attr('fill', 'url(#linear-gradient-1)')
        .style('stroke', '#4d4d4d')
        .style('stroke-width', 1)

    // ...
}

这是生成的文档,没什么特别的:

<svg width="1889" height="400">
    <defs>
        <linearGradient id="linear-gradient-1" x1="0" y1="1" x2="6.123233995736766e-17" y2="0">
            <stop offset="0%" stop-color="#e3e5e8"></stop>
            <stop offset="11%" stop-color="#e6e8ec"></stop>
            <stop offset="59%" stop-color="#eff2fa"></stop>
            <stop offset="100%" stop-opacity="0.6" stop-color="#f2f6ff"></stop>
        </linearGradient>
    </defs>
    <g>
        <g class="node" 
           transform="translate(1113.425033222223,312.1412317958371)">
            <rect width="144" height="42" rx="3" ry="3" 
                  fill="url(#linear-gradient-1)" 
                  style="stroke: #4d4d4d; stroke-width: 1px;"></rect>
            <!-- some other shapes of the node... -->
        </g>
        <!-- etc. etc., some more node groups here... -->
    </g>
</svg>

我尝试过的事情

  • 将引用渐变的元素拉到任何组之外。
  • 用不同的值向 SVG添加version声明(也许它只出现在 1.1 上?)
  • 将引用包含在引号中(即fill="url('#linear-gradient-1')")或省略 id 中的破折号,认为 Webkit 在这里不那么宽松。

笔记

罗伯特·朗森(Robert Longson)在这篇文章中提到了这种情况很重要,而且,很奇怪,当将文档粘贴到空白页面(在 Chrome 的开发工具中)时,线性渐变元素转换为驼峰格式(尽管它没有t 显示在 DOM 视图中,那里都是小写的)。在比较了我的 d3 生成代码和粘贴的静态文档的结果,我发现了这一点。那是怎么回事?


TL;博士

为什么在 Chrome 中运行时生成动态 SVG 渐变不起作用,以及如何解决这个问题?

4

1 回答 1

1

似乎 Safari 开发人员将bug标记为适用于我,基于它在 xhtml 中工作。对于 Safari,您似乎必须使用 mime 类型的 application/xhtml+xml 为您的网页提供服务,或者请求 Safari 开发人员重新打开该错误。FWIW对我来说似乎是一个错误。

于 2013-08-05T13:58:28.693 回答