我正在使用SVG,今天我遇到了一个奇怪的错误。
我的SVG路径(应用了旋转矩阵)在Chrome和Firefox中显示了不同的bbox值。而如果路径没有旋转,则两个浏览器都会给出相同的值。
检查下图: -
如您所见,Firefox生成更准确的结果。 这里是jsfiddle链接: - http://jsfiddle.net/Vjs7p/
以下是两条路径: -
<g id="path_simple">
<path fill="none" stroke="#9400D3" stroke-width="1" stroke-dasharray="1, 0.1" d="M 0 0 L 0.51 0.86 1.01 1.73 1.52 2.59 2.02 3.45 2.53 4.32 3.03 5.18 3.54 6.04 4.04 6.9 4.55 7.77 5.05 8.63 5.56 9.49 6.06 10.36 6.57 11.22 7.07 12.08 7.58 12.95 8.08 13.81 8.59 14.67 9.09 15.53 9.6 16.4 10.1 17.26 10.61 18.12 11.12 18.99 11.62 19.85 12.13 20.71 12.36 21.42 11.36 21.42 10.36 21.42 9.36 21.42 8.36 21.42 7.36 21.42 6.36 21.42 5.36 21.42 4.36 21.42 3.36 21.42 2.36 21.42 1.36 21.42 0.36 21.42 -0.64 21.42 -1.64 21.42 -2.64 21.42 -3.64 21.42 -4.64 21.42 -5.64 21.42 -6.64 21.42 -7.64 21.42 -8.64 21.42 -9.64 21.42 -10.64 21.42 -11.64 21.42 -12.49 21.33 -11.98 20.47 -11.48 19.61 -10.97 18.75 -10.47 17.88 -9.96 17.02 -9.46 16.16 -8.95 15.29 -8.45 14.43 -7.94 13.57 -7.44 12.7 -6.93 11.84 -6.43 10.98 -5.92 10.12 -5.42 9.25 -4.91 8.39 -4.41 7.53 -3.9 6.66 -3.4 5.8 -2.89 4.94 -2.38 4.08 -1.88 3.21 -1.38 2.35 -0.87 1.49 -0.36 0.62 0 0" transform="matrix(1 0 0 1 500 300)"/>
</g>
<g id="path_rotated">
<path fill="none" stroke="#9400D3" stroke-width="1" stroke-dasharray="1, 0.1" d="M 0 0 L 0.51 0.86 1.01 1.73 1.52 2.59 2.02 3.45 2.53 4.32 3.03 5.18 3.54 6.04 4.04 6.9 4.55 7.77 5.05 8.63 5.56 9.49 6.06 10.36 6.57 11.22 7.07 12.08 7.58 12.95 8.08 13.81 8.59 14.67 9.09 15.53 9.6 16.4 10.1 17.26 10.61 18.12 11.12 18.99 11.62 19.85 12.13 20.71 12.36 21.42 11.36 21.42 10.36 21.42 9.36 21.42 8.36 21.42 7.36 21.42 6.36 21.42 5.36 21.42 4.36 21.42 3.36 21.42 2.36 21.42 1.36 21.42 0.36 21.42 -0.64 21.42 -1.64 21.42 -2.64 21.42 -3.64 21.42 -4.64 21.42 -5.64 21.42 -6.64 21.42 -7.64 21.42 -8.64 21.42 -9.64 21.42 -10.64 21.42 -11.64 21.42 -12.49 21.33 -11.98 20.47 -11.48 19.61 -10.97 18.75 -10.47 17.88 -9.96 17.02 -9.46 16.16 -8.95 15.29 -8.45 14.43 -7.94 13.57 -7.44 12.7 -6.93 11.84 -6.43 10.98 -5.92 10.12 -5.42 9.25 -4.91 8.39 -4.41 7.53 -3.9 6.66 -3.4 5.8 -2.89 4.94 -2.38 4.08 -1.88 3.21 -1.38 2.35 -0.87 1.49 -0.36 0.62 0 0" transform="matrix(0.699 -0.715 0.715 0.699 648.544 300.621)"/>
</g>
任何帮助都将受到高度赞赏。
答案 0 :(得分:1)
这是Chrome中的known bug。事件如果边界框应该紧,它不在Chrome中。没有简单的方法,如果你真的需要在chrome中获得一个紧密的边界框,你需要循环遍历元素的所有点并手动计算bbox。如果考虑到所有不同的元素以及计算路径的紧密bbox的困难,那么这可能会导致繁重的工作。
这就是为什么我尽量避免使用边界框的原因。
顺便说一下:您也可以使用getBoundingClientRect()
方法,将坐标中的bbox提供给页面原点,如果使用svgs screenCTM的反转转换该bbox,则绝对有一个边界框svg坐标。这可能会有所帮助,因为getBBox()
返回用户空间中的值,因此相对于元素转换。
根据评论中的要求,这可能是一种计算绝对坐标为<svg>
的边界框的方法。它返回一个数组,包括左上角和右下角。
function bbox (svg, element) {
var mtr = svg.getScreenCTM().inverse(),
bounds = element.getBoundingClientRect(),
p1 = svg.createSVGPoint(),
p2 = svg.createSVGPoint();
p1.x = bounds.left;
p1.y = bounds.top;
p2.x = bounds.right;
p2.y = bounds.bottom;
return [p1.matrixTransform(mtr), p2.matrixTransform(mtr)];
}