我的图形有问题。缩放时,线条越过画布区域的边缘并越过x / y轴。我尝试添加一个clippath,但这似乎不起作用。如果在调试器中检查DOM,则可以看到clippath矩形的位置正好在它需要的位置。

//The canvasGroup is the area between the axis
var clipGroup = canvasGroup.append("clipPath")
                .attr("id", "canvasGroup-clipPath");

var clipRect = clipGroup.append("rect")
                .attr("width", width)
                .attr("height", height);

//Function that does the zooming
function doZoom()
{
    paths.forEach(function(path)
    {
        path.attr("transform", d3.event.transform);
    });

    gX.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
    gY.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));
}

var zoom = d3.zoom()
            .scaleExtent([1, 5])
            .translateExtent([[0, 0], [width, height]])
            .on("zoom", doZoom);

//Register the event listener
canvasGroup.call(zoom);

//now loop over the data sets and plot each one
//For brevity, I'm skipping the loop and only showing the call to create the line
var path = canvasGroup.append("path")
            .attr("clip-path", "url(#canvasGroup-clipPath)")
            .attr("fill", "steelblue")
            .attr("class", "line")
            .attr("id", lineId + "-line")
            .style("stroke", lineColor)
            .style("stroke-width", 1)
            .style("fill", "none");

paths.push(path);
path.attr("d", function(d) { return plotline(i)});


这是它的外观。
变焦前:
javascript - 缩放导致图形超出绘图区域范围-LMLPHP
缩放后:javascript - 缩放导致图形超出绘图区域范围-LMLPHP

最佳答案

该问题是由于在表示数据的路径上设置剪切路径而引起的。在应用剪切路径时,浏览器需要确定<clipPath>元素的内容应使用哪个坐标系。这由clipPathUnits属性控制,该属性默认为userSpaceOnUse


  userSpaceOnUse
  <clippath>元素的内容表示引用<clippath>元素时当​​前用户坐标系中的值(即,通过<clippath>引用clip-path元素的元素的用户坐标系。属性)。


doZoom()函数中变换路径时,实际上是在为该路径建立新的坐标系。并且,除了绘制路径本身外,此坐标系还将用于计算剪切路径的位置和尺寸。因此,通过根据缩放行为变换路径,可以对剪切路径应用相同的变换,从而将其从所需位置移开。

尽管很想将clipPathUnits属性设置为其其他有效值objectBoundingBox,但在这种情况下,这很可能不是您想要的,因为这会使事情变得更加复杂。设置该值时,需要将<clipPath>内容的位置和长度指定为边界框的fractions

知道了这一切,有一个更简单的解决方案!您只需将clip-path应用于在缩放过程中不会变换的元素,例如家长组。鉴于您提供的代码不完整,可以通过将剪切路径设置为canvasGroup来很好地工作:

// Set the clipping path on the parent group.
canvasGroup.attr("clip-path", "url(#canvasGroup-clipPath)")

// Append the path to the group as before.
var path = canvasGroup.append("path")
               .attr("fill", "steelblue")
               .attr("class", "line")
               // ...

09-25 18:09
查看更多