JSFiddle - React, Tailwind, and code Playground
HTML
<div class="box">
<img src="https://loremflickr.com/500/500/" alt="">
</div>
CSS
.box {
position: relative;
width: 300px;
height: 300px;
overflow: hidden;
cursor: move;
outline: 2px solid red;
}
.box img {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
JavaScript
function getMetrics(el) {
var b = el.getBoundingClientRect();
return {
width: b.right - b.left,
height: b.bottom - b.top,
top: b.top + pageYOffset,
left: b.left + pageXOffset
};
}
const box = document.querySelector('.box');
const img = document.querySelector('.box img');
const imgSize = getMetrics(img);
const boxSize = getMetrics(box);
let start = {left: 0, top: 0};
let imgOffset = {x:0, y:0};
let correction = {x:0, y:0};
function move(event){
let mouse = {left: event.screenX, top: event.screenY};
imgOffset.x = mouse.left - start.left + correction.x;
imgOffset.y = mouse.top - start.top + correction.y;
if (imgOffset.x > 0) imgOffset.x = 0;
if (imgOffset.y > 0) imgOffset.y = 0;
if (imgOffset.x < boxSize.width-imgSize.width)
imgOffset.x = boxSize.width-imgSize.width;
if (imgOffset.y < boxSize.height-imgSize.height)
imgOffset.y = boxSize.height-imgSize.height;
img.style.transform = `translate(${imgOffset.x}px, ${imgOffset.y}px)`;
}
box.addEventListener('mousedown', function(event){
start = {left: event.screenX, top: event.screenY};
correction = {x:imgOffset.x, y:imgOffset.y}
document.addEventListener('mousemove', move);
});
document.addEventListener('mouseup', function(){
document.removeEventListener('mousemove', move);
});