react利用svg制作可缩放可移动的圆

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值