forked from nsjcy/frontEnd/nsjcy

liyj
2020-02-11 e60e253cb3ce0597ded89b56a414c731e28c4ff1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React from 'react';
// import { Link } from 'react-router-dom';
// import { Modal } from 'antd-mobile';
// import { Icon } from 'antd';
 
import './index.scss';
 
export default class AttachmentDisplay extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      path: props.path
    };
  }
  rotateImage({ degree, path }) {
    if (degree && !this.rotating) {
      this.rotating = true;
      const canvas = document.createElement('canvas');
      const contex = canvas.getContext('2d');
      const image = new Image();
      image.addEventListener('load', () => {
        const height = image.height;
        const width = image.width;
        if (degree === 180) {
          canvas.width = width;
          canvas.height = height;
        } else {
          canvas.width = height;
          canvas.height = width;
        }
        contex.rotate(degree * Math.PI / 180);
        if (degree === 90) {
          contex.drawImage(image, 0, -height);
        } else if (degree === 180) {
          contex.drawImage(image, -width, -height);
        } else {
          contex.drawImage(image, -width, 0);
        }
        const base64 = canvas.toDataURL('image/jpeg');
        this.rotating = false;
        if (this.props.degree === degree) {
          this.setState({ path: base64 });
        } else this.rotateImage(this.props);
      });
      image.src = path;
    } else this.setState({ path });
  }
 
  componentWillReceiveProps(props) {
    if (this.props.degree !== props.degree) {
      this.rotateImage(props);
    }
  }
 
  render() {
    const { path } = this.state;
    return (
      <div className="attachment-display-main">
        <img src={path} style={{
          maxWidth: "100%"
        }} />
      </div>
    );
  }
 
}