【问题标题】:d3 line chart and clip-pathd3折线图和剪辑路径
【发布时间】:2013-08-08 11:50:37
【问题描述】:

我是 d3 和 svg 的新手

有人可以解释一下在技术上如何使用剪辑路径元素进行拖动/平移

http://jsfiddle.net/MKmHM/1/

var zoom = d3.behavior.zoom()
    .x(x)
    .on("zoom", draw);

svg.append("clipPath")
    .append("rect")
    .attr("id", "clip")
    .attr("width", width)
    .attr("height", height)
    .attr("fill", "blue");

svg.append("rect")
    .attr("class", "pane")
    .attr("width", width)
    .attr("height", height)
    .call(zoom);

svg.append("path")
    .attr("class", "line")
    .attr("clip-path", "url(#clip)");

矩形css

rect.pane {
    cursor: move;
    fill: none;
    pointer-events: all;
}

【问题讨论】:

标签: javascript svg d3.js


【解决方案1】:

魔鬼藏在细节中

我希望你已经自己想出了正确的答案,问题和我的回答之间有一点延迟;)

您的解决方案有效,只是矩形稍微放错了位置并且需要替换两行代码:


svg.append("clipPath")
    .attr("id", "clip")  // <-- we need to use the ID of clipPath
    .append("rect")
    .attr("width", width)
    .attr("height", height)
    .attr("fill", "blue");

  ...
 
  svg.append("path")
    .attr("class", "line")
    .attr("clip-path", "url(#clip)");   <-- here

更正后的代码是here

如何使用剪辑

@Scott Cameron 建议的网站还展示了一些工作示例,它们帮助我弄清楚如何正确地对组和其他元素应用剪辑。

对组应用裁剪的解决方案的好处是我们不必分别对每条网格线和数据线应用。

以下 SVG 示例来自上述site,稍作修改,适用于浏览器和inkscape:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   viewBox="0 0 1100 400" version="1.1">
    <defs>
        <rect id="r1" width="150" height="150" stroke="black" stroke-width="1"/>
        <circle id="r2" cx="100" cy="100" r="100" stroke="black" stroke-width="1"/>
        <circle id="r3" cx="100" cy="100" r="100" stroke="black" stroke-width="1"/>
        <radialGradient id="g1" cx="50%" cy="50%" r="50%" fx="25%" fy="25%">
            <stop stop-color="black" offset="0%"/>
            <stop stop-color="teal" offset="50%"/>
            <stop stop-color="white" offset="100%"/>
        </radialGradient>
        <clipPath id="clip1">
            <path d="M 0 0 L 550 200 L 1100 0"/>
        </clipPath>
    </defs>
    <g clip-path="url(#clip1)">
        <use x="250" y="0" xlink:href="#r1" fill="url(#g1)"/>
        <use x="350" y="150" xlink:href="#r2" fill="url(#g1)"/>
        <use x="580" y="50" xlink:href="#r3" fill="url(#g1)"/>
    </g>
</svg>

我们并不孤单

如果我们在某个时候遇到困难,我们通常需要正确的工具而不是正确的文档:

  • 找到一个解决方案来检查你在做什么是实际发生的事情;

  • 把你的任务分成更小的部分,分别检查;

  • 不要只看你预期错误的地方。

  • 来这里问一些问题,你会得到答案。总有一天;)

【讨论】:

    【解决方案2】:

    以下是 SVG 剪辑工作原理的简短说明:http://www.svgbasics.com/clipping.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多