king
2021-02-05 b2298c8c996dd176c2bd7d424a1aa709cbb97965
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
import React, {Component} from 'react'
import './index.scss'
 
class ImageWrap extends Component {
  componentDidMount () {
    let Img = new Image()
    Img.src = this.props.url
    
    if (!this.ImageWrapDom) return
    
    if (Img.complete) {
      this.setSize(Img.width, Img.height)
    } else {
      Img.onload = () => {
        this.setSize(Img.width, Img.height)
      }
    }
  }
 
  shouldComponentUpdate () {
    return false
  }
 
  setSize = (width, height) => {
    const { clientWidth, clientHeight } = this.ImageWrapDom
 
    if (!clientWidth || !clientHeight || !width || !height) return
 
    let ratio = (width / height) / (clientWidth / clientHeight)
 
    if (ratio > 1.5) {
      let _height = Math.floor(height * (clientWidth / width))
      this.ImageDom.style.height = 'auto'
      this.ImageDom.style.top = ((clientHeight - _height) / 2) + 'px'
    } else if (ratio > 1 && ratio < 1.5) {
      let _width = Math.floor(width / (height / clientHeight))
      this.ImageDom.style.width = _width + 'px'
      this.ImageDom.style.left = '-' + ((_width - clientWidth) / 2) + 'px'
    } else if (ratio < 1) {
      let _height = Math.floor(height / (width / clientWidth))
      this.ImageDom.style.height = _height + 'px'
      this.ImageDom.style.top = '-' + ((_height - clientHeight) / 2) + 'px'
    }
  }
 
  render() {
    return (
      <div className="mk_image-wrap" ref={dom => { this.ImageWrapDom = dom }}>
        <img src={this.props.url} ref={dom => { this.ImageDom = dom }} alt=""/>
      </div>
    )
  }
}
 
export default ImageWrap