如何在缩放后应用 d3.js svg 裁剪

RTM*_*RTM 5 javascript css svg d3.js

我正在尝试将 svg-clippath 与 d3.js 和缩放行为一起使用。以下代码创建一个矩形,然后将由矩形剪切区域对其进行剪切。

<svg class="chart"></svg>
<script>

var width = 800;
var height = 600;

var svg = d3.select(".chart")
        .attr("width", width)
        .attr("height", height)
        .append("g");

var clip = svg.append("defs")
    .append("clipPath")
    .attr("id","clip")
    .append("rect")
    .attr("width",200)
    .attr("height",200)
    .attr("x",100)
    .attr("y",100);


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

function zoomed(){
    container.attr("transform", "translate(" + d3.event.translate
    +")scale(" + d3.event.scale + ")");
    container.attr("clip-path","url(#clip)");
}

    svg.call(zoom);

var container = svg.append("g")
    .attr("clip-path","url(#clip)");

var rect = container.append("rect")
    //.attr("clip-path","url(#clip)")
    .attr("class","bar")
    .attr("x",150)
    .attr("y",150)
    .attr("width",350)
    .attr("height",350);

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

我想要的是在缩放/移动后再次应用剪切(这样我就无法将矩形移出剪切区域,现在我可以毫无问题地执行此操作。)我该怎么做?

我假设当前的行为是由于在转换之前应用剪辑而引起的。

Mah*_*ahé 4

我遇到了同样的问题,并花了最后几个小时试图找出解决方案。显然,剪切路径在变换之前对对象进行操作。因此,我尝试在执行缩放变换时对剪辑对象进行反向变换,这成功了!

它的精神是:

var clip_orig_x = 100, clip_orig_y = 100;
function zoomed() {
    var t = d3.event.translate;
    var s = d3.event.scale;

    // standard zoom transformation:
    container.attr("transform", "translate(" + t +")scale(" + s + ")"); 

    // the trick: reverse transform the clip object!
    clip.attr("transform", "scale(" + 1/s + ")")
        .attr("x", clip_orig_x - t[0]) 
        .attr("y", clip_orig_y - t[1]);
}
Run Code Online (Sandbox Code Playgroud)

其中clip是clipPath中的矩形。由于缩放和平移之间的相互作用,您需要显式设置“x”和“y”,而不是使用变换。

我确信经验丰富的 d3 程序员会想出更好的解决方案,但这可行!