如何通过鼠标移动 SVG 多边形元素?

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

我想用鼠标移动这个多边形。我怎样才能做到这一点? 我想我应该使用 onMouseDown 和 onMouseMove 之类的方法获取新位置并转换 =“translate(x,y) 但我如何通过 JS 做到这一点?

javascript html svg
3个回答
2
投票

您可以使用 jquery UI 中的 draggable。这是您编辑的代码:

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
	<script>
		$( function() {
			$( "#Layer_1" ).draggable();
		} );
	</script>
</head>

<body>
	<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 500 500" style="enable-background:new 0 0 500 500;" xml:space="preserve">
		<polygon class="st0" points=" 0,5 10,0 20,5 10,10" transform="translate(90,95) rotate(0 0 0)" stroke="none" fill="red"/>
	</svg>
</body>
</html>


1
投票

参考下面的内容,它正在工作:

HTML:

<svg id="pointer" height="50" width="50">
    <polygon points="1,1 49,10 20,20 10,49"> 
    <!-- coordinates are in x,y format -->
   <!-- points go clockwise around the polygon -->
</svg>
<a href="bbc.co.uk" target="_blank">bbc</a>

CSS:

#pointer {
  overflow: hidden;
  position: fixed;
  top: 200px;
  left: 200px;
  position: relative;
}
html {
  cursor: none;
}
a {
  font-size: 40px;
}
a:hover {
  cursor: pointer;
}

Javascript:

var mouseX;
var mouseY;
window.onmousemove = handleMouseMove;
function handleMouseMove(event) {
  event = event || window.event;
  document.getElementById('pointer').style.top=event.clientY + "px";
  document.getElementById('pointer').style.left=event.clientX + "px";
}

0
投票

我想将问题扩展到 选择 SVG 内的对象,然后通过拖动来移动它们

我们需要一个变量来记录当前选定的元素。 (

selectedElement
)

并处理

svg.onclick
事件来更新我们选择的元素。

接下来,处理

svg.onmousedown
事件。

触发该事件时,获取鼠标坐标。(

startX, startY = e.clientX, e.clientY
)

然后,在其中添加

mousemove
的事件处理程序。由于我们之前获得了鼠标的初始位置,

我们只需要将mousemove的坐标信息与原始坐标信息结合起来就可以确定位移关系。 (

dx, dy = e.clientX -startX, e.clientY - startY
)

这样就可以正确获取变换所需的偏移数据了。


以下是代码演示: (纯 JavaScript,没有任何其他依赖项。

<!-- 👇 Optional -->
<style>
  .selected {
    stroke-dasharray: 5, 5;
    stroke: red;
    stroke-width: 3;
  }
</style>

<!-- 👇 Optional -->
<label>transform<input type="radio" name="tool" value="transform" checked></label>
<label>OtherTool<input type="radio" name="tool" value="OtherTool"></label>

<svg width="100%" height="100%">

  <!-- 👇 for test only, you can put any component you like. -->
  <rect x="100" y="100" width="100" height="100" fill="blue"/>
  <circle cx="300" cy="300" r="50" fill="green"/>
  <line x1="50" y1="50" x2="450" y2="450" stroke="purple" stroke-width="3"/>
  <polygon points="68.5,50.59375 130.5,50.59375 107.5,89.59375 50.5,86.59375"></polygon>
</svg>


<script>
  const svg = document.querySelector("svg")
  let selectedElement = null

  svg.addEventListener('click', (e) => {
    const target = e.target

    if (selectedElement) {
      selectedElement.classList.remove('selected')
    }

    if (target.tagName.toLowerCase() !== 'svg') {
      target.classList.add('selected')
      selectedElement = target
    } else {
      selectedElement = null
    }
  })

  svg.addEventListener('mousedown', (e) => {
    if (!selectedElement) {
      return
    }

    // get mousedown info
    const startX = e.clientX
    const startY = e.clientY
    const match = selectedElement.style.transform.match(/translate\((-?\d+)px,\s*(-?\d+)px\)/)

    // and we are going to handle mousemove event
    let mousemoveHandler
    const tool = document.querySelector("input[name='tool']:checked").value
    switch (tool) {
      case "transform":
        mousemoveHandler = (e) => {
          const dx = e.clientX - startX
          const dy = e.clientY - startY
          if (match) {
            selectedElement.style.transform = `translate(${dx + Number(match[1])}px, ${dy + Number(match[2])}px)`
          } else {
            selectedElement.style.transform = `translate(${dx}px, ${dy}px)`
          }
        }
        break
    }

    const mouseupHandler = () => {
      document.removeEventListener('mousemove', mousemoveHandler)
      document.removeEventListener('mouseup', mouseupHandler)
    }

    document.addEventListener('mousemove', mousemoveHandler)
    document.addEventListener('mouseup', mouseupHandler)
  })
</script>

© www.soinside.com 2019 - 2024. All rights reserved.