-
Notifications
You must be signed in to change notification settings - Fork 75
/
cropped-image.jsx
91 lines (79 loc) · 1.94 KB
/
cropped-image.jsx
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React from 'react';
import PropTypes from 'prop-types';
import Thumbnail from './thumbnail';
class CroppedImage extends React.Component {
constructor() {
super();
this.state = {
naturalWidth: 0,
naturalHeight: 0,
src: ''
};
}
componentDidMount() {
this.loadImage(this.props.src);
}
componentWillReceiveProps(nextProps) {
if (nextProps.src !== this.props.src) {
this.loadImage(nextProps.src);
}
}
loadImage(src) {
const srcPath = Thumbnail.getThumbnailSrc({
origin: 'https://thumbnails.zooniverse.org',
width: 500,
height: 500,
src
});
const img = new Image();
img.onload = () => {
const { naturalWidth, naturalHeight } = img;
this.setState({ naturalWidth, naturalHeight, src: srcPath });
};
img.src = srcPath;
}
render() {
const { naturalWidth, naturalHeight, src } = this.state;
const min = Math.min(naturalWidth, naturalHeight);
let width = min;
let height = min;
if (this.props.aspectRatio < 1) {
width = this.props.aspectRatio * height;
} else if (this.props.aspectRatio > 1) {
height = this.props.aspectRatio * width;
}
const x = (naturalWidth - width) / 2;
const y = (naturalHeight - height) / 2;
return (
<svg
viewBox={`${x} ${y} ${width} ${height}`}
width={this.props.width}
height={this.props.height}
className={this.props.className}
>
<image
xlinkHref={src}
width={naturalWidth}
height={naturalHeight}
x="0"
y="0"
/>
</svg>
);
}
}
CroppedImage.propTypes = {
aspectRatio: PropTypes.number,
className: PropTypes.string,
height: PropTypes.string,
src: PropTypes.string,
width: PropTypes.string
};
CroppedImage.defaultProps = {
src: '',
aspectRatio: NaN,
className: '',
height: undefined,
width: undefined
};
export default CroppedImage;