Skip to content

Instantly share code, notes, and snippets.

@dmitryshelomanov
Created December 14, 2017 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitryshelomanov/43992487aad24cddd3969f3b8111241b to your computer and use it in GitHub Desktop.
Save dmitryshelomanov/43992487aad24cddd3969f3b8111241b to your computer and use it in GitHub Desktop.
портянка
componentDidUpdate() {
if (this.cloneImage && this.originalWrap) {
this.originalImage = this.originalWrap.querySelector('img')
this.addEventListener()
this.clearStyles()
}
}
componentWillUnmount() {
this.removeListeners()
}
addEventListener = () => {
this.originalWrap.addEventListener('mousedown', this.imageHandleDown)
this.originalWrap.addEventListener('mouseup', this.imageHandleUp)
this.originalWrap.addEventListener('mousewheel', this.scale)
}
removeListeners = () => {
this.originalWrap.removeEventListener('mousedown', this.imageHandleDown)
this.originalWrap.removeEventListener('mouseup', this.imageHandleUp)
this.originalWrap.removeEventListener('mousewheel', this.scale)
}
imageHandleDown = (e) => {
this.setState({ isPressed: true }, () => {
this.originalWrap.onmousemove = this.mouseMove
})
}
imageHandleUp = () => {
this.setState({ isPressed: false })
}
mouseMove = (e) => {
if (this.state.isPressed) {
const { offsetX, offsetY } = this.getMouseCoord(e)
const { oldX, oldY } = this.state
oldX > offsetX
? this.moveX('left')
: this.moveX('right')
oldY > offsetY
? this.moveY('bottom')
: this.moveY('top')
this.setState({
oldX: offsetX,
oldY: offsetY
})
}
}
moveX = (direction) => {
direction === 'right'
? this.originalImage.style.left = `${parseInt(this.originalImage.style.left || 0) + this.state.swipeSpeed}px`
: this.originalImage.style.left = `${parseInt(this.originalImage.style.left || 0) - this.state.swipeSpeed}px`
}
moveY = (direction) => {
direction === 'top'
? this.originalImage.style.top = `${parseInt(this.originalImage.style.top || 0) + this.state.swipeSpeed}px`
: this.originalImage.style.top = `${parseInt(this.originalImage.style.top || 0) - this.state.swipeSpeed}px`
}
scale = (e) => {
const { deltaY } = e
const { oldScale } = this.state
e.preventDefault()
if (deltaY > 0) {
console.log(oldScale)
this.setState({ oldScale: oldScale - .2 }, () => {
this.originalImage.style.transform = `scale(${oldScale})`
})
} else {
this.setState({ oldScale: oldScale + .2 }, () => {
this.originalImage.style.transform = `scale(${oldScale})`
})
}
}
getMouseCoord = (e) => ({
px: e.x,
py: e.y,
offsetX: e.offsetX,
offsetY: e.offsetY
})
clearStyles = () => {
this.originalImage.removeAttribute('style')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment