Move (drag, pan) and zoom object (image or div)
HTML
<div id="container">
<img id="drag-img" src="http://www.patsoy.com/p/2015/09/geometric-patterns-f03phtdx.jpg" />
</div>
<input type="button" id="zoomout" class="button" value="Zoom out">
<input type="button" id="zoomin" class="button" value="Zoom in">
CSS
#drag-img {
cursor: move;
position: relative;
top: 50%;
transform: translate(-50%, -50%);
left: 50%;
height:100%;
}
#container {
overflow: hidden;
background: red;
height: 500px;
width: 500px;
}
.button {
width: 200px;
height: 50px;
}
JavaScript
var img_ele = null,
x_cursor = 0,
y_cursor = 0,
x_img_ele = 0,
y_img_ele = 0;
function zoom(zoomincrement) {
img_ele = document.getElementById('drag-img');
var pre_width = img_ele.getBoundingClientRect().width,
pre_height = img_ele.getBoundingClientRect().height;
img_ele.style.width = (pre_width * zoomincrement) + 'px';
img_ele.style.height = (pre_height * zoomincrement) + 'px';
img_ele = null;
}
document.getElementById('zoomout').addEventListener('click', function() {
zoom(0.5);
});
document.getElementById('zoomin').addEventListener('click', function() {
zoom(1.5);
});
function start_drag() {
img_ele = this;
x_img_ele = x_cursor - img_ele.offsetLeft;
y_img_ele = y_cursor - img_ele.offsetTop;
}
function stop_drag() {
img_ele = null;
}
function while_drag() {
x_cursor = window.event.clientX;
y_cursor = window.event.clientY;
if (img_ele !== null) {
img_ele.style.left = (x_cursor - x_img_ele) + 'px';
img_ele.style.top = (y_cursor - y_img_ele) + 'px';
}
}
document.getElementById('drag-img').addEventListener('mousedown', start_drag);
document.getElementById('drag-img').addEventListener('mousemove', while_drag);
document.getElementById('drag-img').addEventListener('mouseup', stop_drag);
/*document.getElementById('drag-img').onmousedown = function() {
start_drag(this);
console.log("start: " + start_drag(this));
}
document.getElementById('drag-img').onmousemove = function() {
while_drag();
console.log("while: " + while_drag());
}
document.getElementById('drag-img').onmouseup = function() {
stop_drag();
console.log("stop: " + stop_drag());
}*/