缩放查看图片功能小记

  1. 1. 放大查看图片
  2. 2. 移动图片
  3. 3. 图片

放大查看图片

  • 滚轮滚动时改变图片的zoom
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* handle zoom image */
this.handleZoom = (event) => {
if (this.refDetailImage) {
if (this.state.thumbPath) this.setState({ thumbPath: '' })
let zoom = this.refDetailImage.style.zoom
zoom *= 0.6 + (event.wheelDelta + 240) / 600
if (zoom <= 1) {
zoom = 1
this.refTransition.style.transform = this.degRotate
this.dragPosition.left = 0
this.dragPosition.top = 0
} else if (zoom > 10000) {
zoom = 10000
} else {
this.dragPosition.left *= 0.6 + (event.wheelDelta + 240) / 600
this.dragPosition.top *= 0.6 + (event.wheelDelta + 240) / 600
this.refTransition.style.transform = `translate(${this.dragPosition.left}px,${this.dragPosition.top}px) ${this.degRotate}`
}
// debug('onMouseWheel', event.wheelDelta, zoom)
this.refContainer.style.overflow = ''
this.refDetailImage.style.zoom = zoom
}
}

移动图片

  • zoom > 1 时可平移图片
1
2
3
4
5
6
7
8
9
10
11
12
13
/* handle drag image when zoom */
this.dragImage = (event) => {
// debug('this.dragImage before', this.degRotate)
if (event.target.style.zoom > 1 && this.state.drag) {
const style = this.refTransition.style
this.dragPosition.left += this.dragPosition.x ? event.clientX - this.dragPosition.x : 0
this.dragPosition.top += this.dragPosition.y ? event.clientY - this.dragPosition.y : 0
this.dragPosition.x = event.clientX
this.dragPosition.y = event.clientY
style.transform = `translate(${this.dragPosition.left}px,${this.dragPosition.top}px) ${this.degRotate}`
// debug('this.dragImage', event.clientX, event.clientY, this.dragPosition.left, this.dragPosition.top)
}
}

图片

  • 需注意draggable={false}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{/* DetailImage */}
<div
style={{ position: 'absolute', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
ref={ref => (this.refTransition = ref)}
>
{
this.state.detailPath &&
<img
height={this.exifOrientation % 2 === 0 ? this.photoWidth : this.photoHeight}
width={this.exifOrientation % 2 === 0 ? this.photoHeight : this.photoWidth}
alt="DetailImage"
src={this.state.detailPath}
ref={ref => (this.refDetailImage = ref)}
style={{ zoom: 1, transition: 'translate .5s cubic-bezier(0.0, 0.0, 0.2, 1)' }}
onMouseDown={() => this.setState({ drag: true })}
onMouseUp={() => { this.setState({ drag: false }); this.dragPosition.x = 0; this.dragPosition.y = 0 }}
onMouseMove={this.dragImage}
draggable={false}
/>
}
</div>