zoompantest

by mrjordy

HTML

<div id="container">
  <img ondragstart="return false" 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;
  width: 500px;
  height: 500px;
}

#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 = window.event.clientX - document.getElementById('drag-img').offsetLeft;
  y_img_ele = window.event.clientY - document.getElementById('drag-img').offsetTop;

}

function stop_drag() {
  img_ele = null;
}

function while_drag() {
  var x_cursor = window.event.clientX;
  var y_cursor = window.event.clientY;
  if (img_ele !== null) {
    img_ele.style.left = (x_cursor - x_img_ele) + 'px';
    img_ele.style.top = ( window.event.clientY - y_img_ele) + 'px';

      console.log(img_ele.style.left+' - '+img_ele.style.top);

  }
}

document.getElementById('drag-img').addEventListener('mousedown', start_drag);
document.getElementById('container').addEventListener('mousemove', while_drag);
document.getElementById('container').addEventListener('mouseup', stop_drag);