1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- export type ImagePreviewOption = {
- maxZoom: number
- minZoom: number
- fullScreen: boolean
- }
- class ImagePreview {
- private currentX: number = 0
- private currentY: number = 0
- private xOffset: number = 0
- private yOffset: number = 0
- private initialX: number = 0
- private initialY: number = 0
- private maxZoom: number = 6
- private minZoom: number = 0.5
- private initZoom: number = 1
- private initRotate: number = 0
- private isMove: boolean = false
- private el: HTMLElement
- constructor(option?: ImagePreviewOption) {
- this.maxZoom = option?.['maxZoom'] ?? 6
- this.minZoom = option?.['minZoom'] ?? 0.5
- }
- bindMouseEvent(el: HTMLElement) {
- this.el = el
- this.el.addEventListener('mousedown', (event: any) => {
- this.downHandler(event)
- })
- this.el.addEventListener('mousemove', (event: any) => {
- this.moveHandler(event)
- })
- this.el.addEventListener('mouseup', (event: any) => {
- this.upHandler(event)
- })
- this.el.addEventListener('mouseleave', (event: any) => {
- this.upHandler(event)
- })
- }
- downHandler(event: any) {
- event.preventDefault()
- if (event.button === 0) {
- this.isMove = true
- this.initialX = event.clientX - this.xOffset
- this.initialY = event.clientY - this.yOffset
- this.el.style.cursor = 'move'
- }
- }
- moveHandler(event: any) {
- event.preventDefault()
- if (this.isMove) {
- this.currentX = event.clientX - this.initialX
- this.currentY = event.clientY - this.initialY
- this.xOffset = this.currentX
- this.yOffset = this.currentY
- this.setTranslate()
- }
- }
- upHandler(event) {
- if (event.button === 0) {
- this.isMove = false
- this.el.style.cursor = 'pointer'
- }
- }
- zoomHandler(num: number) {
- if (num === 1 && this.initZoom >= this.maxZoom) return
- if (num === -1 && this.initZoom <= this.minZoom) return
- this.initZoom = this.initZoom + num * 0.5
- this.setTranslate()
- }
- rotateHandler = (num: number) => {
- if (num !== 0) {
- this.initRotate += num * 90
- this.setTranslate()
- } else {
- //重置
- this.initRotate = 0
- this.currentX =
- this.currentY =
- this.xOffset =
- this.yOffset =
- this.initialX =
- this.initialY =
- 0
- this.initZoom = 1
- this.el.style.transform = 'none'
- }
- }
- setTranslate() {
- this.el.style.transform = `translate3d(${this.currentX}px, ${this.currentY}px, 0) scale(${this.initZoom}) rotate(${this.initRotate}deg)`
- }
- }
- export default ImagePreview
|