首页 > 解决方案 > 更新 SVG 元素的转换时,Firefox 会移动剪辑路径,而 Chromium 不会 - 这是正确的,什么是可移植的解决方案?

问题描述

更新剪辑的 SVG 元素的变换时,Firefox 和 Chromium 有不同的行为。Firefox 会移动剪辑路径,而 Chromium 不会。

示例代码:

<!doctype html>
<html>
  <head>
    <meta charset='utf-8'>
    <title></title>
  </head>
  <body>
    <button id='button'>Click to translate</button>
    <br/>
    <svg width='500px' height='500px'>
      <g clip-path='polygon(0 0, 50 0, 50 50, 0 50)'>
        <g transform='translate(25 25)' id='group'>
          <rect x='0' y='0' width='50' height='50' fill='red'></rect>
        </g>
      </g>
    </svg>
    <script>
      var b = document.getElementById('button');
      var g = document.getElementById('group');
      b.onclick = function(event) {
          g.setAttribute('transform', 'translate(0, 0)');
      };
    </script>
  </body>
</html>

JSFiddle:https ://jsfiddle.net/TheAspiringHacker/w7ymfn3s/1/

最外面的g元素根据边长为 50 的正方形进行裁剪。要确定将裁剪多边形放置在什么坐标处,浏览器似乎会找到包含要呈现的内容的矩形的左上角。由于有一个g平移的内部元素 (25, 25) 包含rect在 (0, 0) 处的 a,因此裁剪多边形放置在 (25, 25) 处。

单击按钮时,内部g元素的变换将更改为 (0, 0)。

单击按钮时,Firefox 和 Chromium 具有不同的行为。在 Firefox 中,剪辑路径的位置会相应更改以匹配矩形的新位置。在 Chromium 中,它不是,导致矩形的一部分被剪裁。我已经使用 Firefox 66.0.2 和 Chromium 73.0.3683.86 测试了代码。

根据规范,哪种行为是正确的行为?

我想剪辑一个我以编程方式翻译的元素。考虑到 Firefox 和 Chromium 似乎有不同的行为,有什么解决方案可以让我获得跨浏览器的东西?

标签: domsvgcross-browser

解决方案


我会先定义clipPath:

<clipPath id="poly">
   <polygon points="0 0, 50 0, 50 50, 0 50"></polygon>
</clipPath>

然后将其应用于组:

 <g clip-path="url(#poly)">

var b = document.getElementById('button');
      var g = document.getElementById('group');
      b.onclick = function(event) {
          g.setAttributeNS(null,'transform', 'translate(0, 0)');
      };
svg{border:1px solid}
    <button id='button'>Click to translate</button>
    <br/>
    <svg width='500px' height='500px'>
    <clipPath id="poly">
      <polygon points="0 0, 50 0, 50 50, 0 50"></polygon>
    </clipPath>
    <g clip-path="url(#poly)">
        <g transform='translate(25 25)' id='group'>
          <rect x='0' y='0' width='50' height='50' fill='red'></rect>
        </g>
      </g>
      

    </svg>


推荐阅读