Skip to content

Instantly share code, notes, and snippets.

@notgiorgi
Created August 4, 2017 13:59
Show Gist options
  • Save notgiorgi/57f0e431f43907ad249bafba67b1000b to your computer and use it in GitHub Desktop.
Save notgiorgi/57f0e431f43907ad249bafba67b1000b to your computer and use it in GitHub Desktop.
Pure JS image zoom
<figure
id="figure"
>
<img
id="img"
src=""
/>
</figure>
Magnification level: <input id="input" type="number" value="200" />
<br />
Image url: <input
id="input2"
type="text"
value="https://res.cloudinary.com/active-bridge/image/upload/slide1.jpg"
/>
console.clear()
const { Observable } = Rx
optimizeUIEvent('mousemove', document)
const figure = document.getElementById('figure')
const img = document.getElementById('img')
const input = document.getElementById('input')
const input2 = document.getElementById('input2')
const getMouseMove$ = () => Observable.fromEvent(document, 'mousemove')
const mouseOut$ = Observable.fromEvent(figure, 'mouseout')
const moseOver$ = Observable.fromEvent(figure, 'mouseover')
.switchMap(() =>
getMouseMove$()
.takeUntil(mouseOut$)
)
.map(zoom(figure))
.forEach(({ x, y }) => {
figure.style.backgroundPosition = `${x}% ${y}%`
})
const magnificationInput$ = Observable.fromEvent(input, 'keyup')
magnificationInput$
.map(e => e.target.value)
.startWith("200")
.forEach(
val => {
figure.style.backgroundSize = `${val}%`
}
)
const imageInput$ = Observable.fromEvent(input2, 'keyup')
imageInput$
.map(e => e.target.value)
.startWith("https://res.cloudinary.com/active-bridge/image/upload/slide1.jpg")
.forEach(
url => {
figure.style.backgroundImage = `url(${url})`
img.src = url
}
)
function zoom(figure) {
return e => {
let offsetX, offsetY, x, y
offsetX = e.offsetX
offsetY = e.offsetY
x = offsetX / figure.offsetWidth * 100
y = offsetY / figure.offsetHeight * 100
return { x, y }
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://unpkg.com/rx@4.1.0/dist/rx.all.min.js"></script>
<script src="https://unpkg.com/optimize-ui-event@0.0.2"></script>
figure {
display: block;
img:hover {
opacity: 0;
cursor: zoom-in;
}
img {
transition: opacity .5s;
display: block;
width: 100%;
}
position: relative;
width: 500px;
overflow: hidden;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment