react利用svg制作可缩放可移动的圆
鼠标移到中部,变为可移动状态,圆可移动;
鼠标移到边缘,变为缩放状态,可放大缩小。
import React from 'react'
class Test1 extends React.Component {
constructor() {
super()
this.state = {
move_style: { cursor: 'col-resize' }
}
}
zoom = () => {
const svg2 = document.getElementById('svg2')
let circle = document.getElementById('circle1')
let isDown = false
let isMove = false
let m_move_x, m_move_y, m_down_x, m_down_y
let move_div
svg2.onmousedown = () => {
isDown = true
}
circle.onmouseup = () => {
isDown = false
}
svg2.onmousemove = () => {
move_div = document.getElementById('circle1')
//获取鼠标移动实时坐标
m_move_x = event.pageX
m_move_y = event.pageY
let newR = Math.sqrt(
(m_move_x - circle.getAttribute('cx')) *
(m_move_x - circle.getAttribute('cx')) +
(m_move_y - circle.getAttribute('cy')) *
(m_move_y - circle.getAttribute('cy'))
)
if (newR > 50 && newR < circle.getAttribute('r')) {
isMove = true
this.setState({ move_style: { cursor: 'col-resize' } })
} else if (newR > circle.getAttribute('r')) {
this.setState({ move_style: { cursor: 'default' } })
} else {
isMove = false
this.setState({ move_style: { cursor: 'move' } })
}
//鼠标按下时移动才触发
if (isDown) {
if (isMove) {
circle.setAttribute('r', newR)
} else {
circle.setAttribute('cx', m_move_x)
circle.setAttribute('cy', m_move_y)
}
}
}
}
componentDidMount() {
this.zoom()
}
render() {
return (
<div>
<svg id="svg2" width="100%" height="620" style={this.state.move_style}>
<circle
style={this.state.move_style}
id="circle1"
cx="300"
cy="200"
r="100"
stroke="black"
strokeWidth="1"
fill="#EED5D2"
/>
</svg>
</div>
)
}
}
export default Test1