更新SVG元素的转换时,Firefox会移动剪辑路径,而Chromium则不会 - 这是正确的,什么是便携式解决方案?

问题描述 投票:0回答:1

当更新剪切的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的正方形进行裁剪。要确定放置剪裁多边形的坐标,浏览器似乎找到包含要渲染内容的矩形的左上角。由于在(0,0)处存在包含g的内部rect元素(25,25),因此剪切多边形位于(25,25)处。

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

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

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

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

dom svg cross-browser
1个回答
1
投票

我先定义一下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>
© www.soinside.com 2019 - 2024. All rights reserved.