dom - 更新 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 似乎有不同的行为,有什么解决方案可以让我获得跨浏览器的东西?
解决方案
我会先定义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>
推荐阅读
- python - concurrent.futures:“进程池中的进程在未来正在运行或挂起时突然终止。”
- jquery - 我想防止点击,但允许拖放 jQuery 元素
- netty - Netty writeAndFlush 返回 false
- javascript - 字符串中的数字总和 - Javascript
- html - CSS3 中的@keyframes 标识符规则是什么?
- javascript - 未处理的拒绝错误:发送后无法设置标头。为什么会这样?
- spring - 什么类实现了spring框架Autowired
- reactjs - 如何在 React 或 Vue 中的表格内构建组件渲染多行
- clips - CLIPS(templates) - 家庭关系:在编写规则时处理模板和初始事实的麻烦
- c# - 在 Unity 中始终如一地将角色推向一个方向