如何把一个svg中的部分内容拷贝到另一个svg中间位置

比如,把这个svg中的rect拿出来 拷贝到另一个svg的中间位置

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" version="1.1">

<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1; stroke:rgb(0,0,0)"/>

</svg>
阅读 2.2k
2 个回答

https://codepen.io/brendanfic...

<body>
  <svg id="svg1"  style="border: 1px solid red;" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" version="1.1">
    <rect x="10" y="10" transform="translate(20, 20)" width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1; stroke:rgb(0,0,0)"/>
  </svg>
  <svg id="svg2" style="border: 1px solid blue;" xmlns="http://www.w3.org/2000/svg" width="200px" height="200px" version="1.1">
  </svg>
  <button onclick="copyRect()">copyRect</button>
  <script>
    function copyRect() {
      const rect = document.querySelector('#svg1 rect').cloneNode()
      const svg2 = document.querySelector('#svg2')
      let scale = 0.5
      let x = (svg2.clientWidth / 2) - (rect.width.baseVal.value * scale / 2)
      let y = (svg2.clientHeight / 2) - (rect.height.baseVal.value * scale / 2)
      rect.x.baseVal.value = 0
      rect.y.baseVal.value = 0
      rect.setAttribute('transform', `translate(${x},${y}) scale(${scale})`)
      svg2.appendChild(rect)
    }
  </script>
</body>

svg 在浏览器中也是 dom ,svg dom,所以你用 css 也是可以移动它的位置的,具体还是得看你需求。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题