How to apply d3.js svg clipping after zooming

后端 未结 1 776
清歌不尽
清歌不尽 2021-01-06 09:53

I am trying to use an svg-clippath with d3.js and the zoom behaviour. The following code creates a rectangle, which will then be clipped by a rectangualar clipping region. <

相关标签:
1条回答
  • 2021-01-06 10:40

    I had the same problem and spent the last couple of hours trying to figure out a solution. Apparently, the clip-path operates on the object prior to transformation. So I tried to reverse-transform the clip object when performing the zoom transformation, and this worked !

    It is something in the spirit of:

    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]);
    }
    

    where clip is the rectangle in the clipPath. Because of interactions between zooming and translation, you need to set "x" and "y" explicitly instead of using transform.

    I am sure experienced d3 programmers out there will come up with a better solution, but this works !

    0 讨论(0)
提交回复
热议问题