javascript - 使用javascript翻转SVG对象

标签 javascript html svg

我在尝试使用 javascript 翻转 SVG 对象时遇到问题。我已经搜索了几种翻转 svg 对象方向的方法,例如:

<g id = "object1" transform = "scale(-1,1) translate(-100,0)">
//code of svg object
</g>

当我试图在我的 js 文件中应用类似的代码时,它无法翻转对象。

svgdoc = evt.target.ownerDocument;
var node = svgdoc.getElementById("object1");
node.onclick = function(){
  node.style.setProperty("scale", "(-1,1)",null);
  node.style.setProperty("translate", "(-100,1)",null);
}

附注svg对象编码在.svg文件中,上面的js代码编码在另一个.js文件中

最佳答案

对于 SVG 元素,您需要使用 .setAttribute 而不是 .style

虽然都是DOM节点,但是SVG元素使用inline attributes对于这些操作。

除此之外,您还需要翻译您的项目以抵消应用缩放时的位置变化

document.querySelector('#group').addEventListener('click', function() {
  this.setAttribute('transform', 'scale(-1, 1) translate(-100, 0)')
})
<svg viewBox="0 0 195 150" xmlns="http://www.w3.org/2000/svg">
   <g id="group" stroke="green" fill="white" stroke-width="5">
     <circle cx="0" cy="25" r="15"/>
     <circle cx="20" cy="25" r="15"/>
     <circle cx="40" cy="25" r="15"/>
     <circle cx="60" cy="25" r="15"/>
     <circle cx="80" cy="25" r="15"/>
     <circle cx="100" cy="25" r="15"/>
   </g>
</svg>

关于javascript - 使用javascript翻转SVG对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47119064/

相关文章:

html - SVG 矩形与 div 与 Canvas

css - 当笔画有一个 dasharray 时,我怎样才能做一个 SVG 路径绘图动画?

javascript - 如何测试 axios 包装器

javascript - 浏览器链接和 Web 窗体(设计模式不适用于 ASP.NET Web 窗体)

javascript - 获取不同图层 Konva JS 中形状的属性

html - 第二个 CSS 样式表优先于第一个

javascript - 给灰度图像着色

javascript - 重用 Angular 和 html 的冗余函数

javascript - 为什么提交按钮会导致其他选项卡?

javascript - 在 Div Javascript 中获取值