如何应用d3.js svg剪辑缩放后 [英] How to apply d3.js svg clipping after zooming
问题描述
我试图使用svg-clippath与d3.js和缩放行为。
以下代码创建了一个矩形,然后将被矩形剪切区域剪切。
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.
<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>
我想要的是剪辑在缩放/移动后再次应用b $ b将剪辑区域的矩形移出剪辑区域,现在我可以没有任何问题。)我该如何做?
What I want is for the clipping to be applied again after zooming / moving (so that I cannot move the rectangle outh of the clipping region, which right now i can do without any problems.) How do I do that?
我假设当前行为是由在转换之前应用剪切的事实引起的。
I am assuming that the current behaviour is caused by the fact that the clipping is applied before the transformation.
推荐答案
我有同样的问题,花了最后几个小时试图找出一个解决方案。显然,剪辑路径对对象先于进行转换。因此,当执行缩放变换时,我尝试反向变换剪辑对象,并且这个工作起来了!
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 !
这是一种精神:
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]);
}
其中clip是clipPath中的矩形。由于缩放和平移之间的交互,您需要显式设置x和y,而不是使用transform。
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.
我相信经验丰富的d3程序员会提出一个更好的解决方案,但这是有效的!
I am sure experienced d3 programmers out there will come up with a better solution, but this works !
这篇关于如何应用d3.js svg剪辑缩放后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!