react里面实现图片旋转效果

1.新建文件夹rotate.js

class RotateImg {
     
  constructor() {
     
      this.el = null;
  }
  init(cls) {
     
      this.el = document.getElementById(cls);
      // this.el = document.getElementsByClassName(cls)[0];
      return this;
  }
  DragStart() {
     
     this.el.onmousedown = (evt) => {
     
          var e = evt || window.event;

          var downX=e.pageX
          var downY=e.pageY

          this.DragIng();
          this.DragEnd(downX,downY)
      }
  }
  DragIng() {
     
      document.onmousemove = (evt) => {
     
          var e = evt || window.event;
      }
  }
  DragEnd(x,y) {
     
      document.onmouseup=(e) => {
     
          document.onmouseup = document.onmousemove = null;

          var upX=e.pageX
          var upY=e.pageY

          let disX=Math.abs(upX-x)
          let disY=Math.abs(upY-y)
          let z=Math.sqrt(disX*disX+disY*disY)

          let angle=Math.round(Math.asin(disY/z)/Math.PI*180)

          if(upX-x>0){
     
            this.el.style.transform=`rotate(${
       angle}deg)`
          }else{
     
            this.el.style.transform=`rotate(-${
       angle}deg)`
          }


      }
  }
}

export default new RotateImg()

2.使用

<button onClick={
     this.handleRotate}>图片旋转</button>

<Modal
    closable={
     false}
    destroyOnClose
    footer={
     null}
    onCancel={
     this.handleCancelRotate}
    onOk={
     this.handleOkRotate}
    visible={
     this.state.visibleRotate}
>
    <div id="rotateImg"
        style={
     {
     background:'url('+require('../../img/111.jpeg')+')',width:480,backgroundSize:'cover',height:600}}
    >

    </div>

3.index.js文件引入,调用

import Rotate from '../../js/rotate'

    handleRotate=()=>{
     
        this.setState({
     
            visibleRotate:true
        })

        setTimeout(()=>{
     
            Rotate.init('rotateImg').DragStart()
        },1000)
  }

Modal组件的背景颜色是白色的,最好设置为透明
效果如图:
react里面实现图片旋转效果_第1张图片

你可能感兴趣的:(react,reactjs)