Move (drag/pan) and zoom object (image or div) in pure js
Asked Answered
J

2

7

I'm working on a little script that makes an object (div or img) moveable and zoomable within a given frame.

However I came across a few problems I'm not really sure of, because I'm a javascript beginner - so explanation of why those problems occure would be appreciated.

Problems:

  1. Calling the functions start_drag(), while_drag() and stop_drag() returns undefined - why is that? What should be returned?
  2. The dragging and moving of the image does not work correctly - instead of clicking the mousebutton down and starting to move the image around, I have to click once and then start moving. Although I bound the mousedown event to the image. What did I do wrong?
  3. Why is the moving part not working on mobile (the zooming works!)?

Please see my fiddle: https://jsfiddle.net/pow4ngbw/15/

Johore answered 7/2, 2016 at 10:22 Comment(4)
your start_drag(), while_drag() and stop_drag() functions doesn't return anythig explicitally, therefore they "return" undefuned...Showoff
It doesnt work on mobile because it doesnt have touch eventsBrumby
take a look at: #30818034Showoff
thanks @Showoff - however I need to have it in vanilla js not jqueryJohore
B
8

Working fine now, was mainly the image css but found several errors (see the new img attribute), also added a few tweaks to make the dragging smoother.

 
    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);
 #drag-img {
      cursor: move;
      position: relative;
      width: 500px;
      height: 500px;
    }
    
    #container {
      overflow: hidden;
      background: red;
      height: 500px;
      width: 500px;
    }
    
    .button {
      width: 200px;
      height: 50px;
    }
 <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">
  
Brumby answered 7/2, 2016 at 12:38 Comment(8)
Didn't add touch events so still wont work on mobilesBrumby
great thanks a lot @Bug! I made a new fiddle jsfiddle.net/azyb9mzz could you please explain why you hooked the eventlisteners to the container div and not the img object itself? and I tried adding touchevents (touchstart, touchmove and touchend) to it - which seems to partially work because I get the correct console alerts. however the style position of the image is not updated and thus not moved... but why?Johore
based on the work of @Brumby I implemented touch functionality: jsfiddle.net/j8kLz6wm/1 thanks once again!Johore
I hooked into the container events because if you move the mouse quickly the dragging stalled, even better would be to use the events of the bodyBrumby
I notice a slight jump when you first start dragging, add +8 to x_img_ele and y_img_ele in your start_drag eventBrumby
i have the fiddle at jsfiddle.net/shabeerak/ne8em13t/5 copied from @Bug's answer and it works like a charm. Thank you! The slight problem that is see here is that the jump is big higher on drag_start when the container position is not at x=0 & y=0. Appreciate if someone could help me figure that part. Hope its a quick fix.Harmonium
Anybody wanting to see a demo of this solution please remove the margin for #container and see how nicely its done from fiddle jsfiddle.net/shabeerak/ne8em13t/5Harmonium
can zoomout restricted to the container width and heightWold
A
1

I have taken Bug's code and added features that I need and were requested in the comments. I have updated it to: Keep the image always within the container when zooming or panning, and to encapsulate the implementation inside the zoomer object to keep the global environment clean.

<!DOCTYPE html>
<html>
<head>
<style>
#zoom-img {
  cursor: move;
  position: relative;
  width: 500px;
  height: 500px;
}

#zoom-container {
  overflow: hidden;
  background: red;
  height: 500px;
  width: 500px;
}

.button {
  width: 100px;
  height: 50px;
}
</style>
</head>
<body id="fullbody">
<div id="zoom-container">
  <img ondragstart="return false" id="zoom-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/17/Cordillera_de_los_Andes.jpg/1024px-Cordillera_de_los_Andes.jpg" />
</div>
<input type="button" id="zoomout" class="button" value="Zoom out">
<input type="button" id="zoomin" class="button" value="Zoom in">
</body>
</html>
<script>
//
//    This file is derived from the javascript portion of the drag-zoom example
//    at the web site: 
//     https://mcmap.net/q/901500/-move-drag-pan-and-zoom-object-image-or-div-in-pure-js
//

var zoomer = (function () {
    var img_ele = null,
      x_cursor = 0,
      y_cursor = 0,
      x_img_ele = 0,
      y_img_ele = 0,
      orig_width = document.getElementById('zoom-img').getBoundingClientRect().width,
      orig_height = document.getElementById('zoom-img').getBoundingClientRect().height,
      current_top = 0,
      current_left = 0,
      zoom_factor = 1.0;

    return {
        zoom: function (zoomincrement) {
            img_ele = document.getElementById('zoom-img');
            zoom_factor = zoom_factor + zoomincrement;
            if (zoom_factor <= 1.0)
            {
                zoom_factor = 1.0;
                img_ele.style.top =  '0px';    
                img_ele.style.left = '0px';
            }
            var pre_width = img_ele.getBoundingClientRect().width, pre_height = img_ele.getBoundingClientRect().height;
            console.log('prewidth='+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';
            var new_width = (orig_width * zoom_factor);
            var new_heigth = (orig_height * zoom_factor);

                console.log('postwidth='+img_ele.style.width+'; postheight ='+img_ele.style.height);

            if (current_left < (orig_width - new_width))
            {
                current_left = (orig_width - new_width);
            }
            if (current_top < (orig_height - new_heigth))
            {
                current_top = (orig_height - new_heigth);
            }
            img_ele.style.left = current_left + 'px';
            img_ele.style.top = current_top + 'px';
            img_ele.style.width = new_width + 'px';
            img_ele.style.height = new_heigth + 'px';

            img_ele = null;
        },

        start_drag: function () {
          if (zoom_factor <= 1.0)
          {
             return;
          }
          img_ele = this;
          x_img_ele = window.event.clientX - document.getElementById('zoom-img').offsetLeft;
          y_img_ele = window.event.clientY - document.getElementById('zoom-img').offsetTop;
          console.log('img='+img_ele.toString()+'; x_img_ele='+x_img_ele+'; y_img_ele='+y_img_ele+';')
          console.log('offLeft='+document.getElementById('zoom-img').offsetLeft+'; offTop='+document.getElementById('zoom-img').offsetTop)
        },

        stop_drag: function () {
          if (img_ele !== null) {
            if (zoom_factor <= 1.0)
            {
              img_ele.style.left = '0px';
              img_ele.style.top =  '0px';      
            }
            console.log(img_ele.style.left+' - '+img_ele.style.top);
            }
          img_ele = null;
        },

        while_drag: function () {
            if (img_ele !== null)
            {
                var x_cursor = window.event.clientX;
                var y_cursor = window.event.clientY;
                var new_left = (x_cursor - x_img_ele);
                if (new_left > 0)
                {
                    new_left = 0;
                }
                if (new_left < (orig_width - img_ele.width))
                {
                    new_left = (orig_width - img_ele.width);
                }
                var new_top = ( y_cursor - y_img_ele);
                if (new_top > 0)
                {
                    new_top = 0;
                }
                if (new_top < (orig_height - img_ele.height))
                {
                    new_top = (orig_height - img_ele.height);
                }
                current_left = new_left;
                img_ele.style.left = new_left + 'px';
                current_top = new_top;
                img_ele.style.top = new_top + 'px';

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

document.getElementById('zoomout').addEventListener('click', function() {
  zoomer.zoom(-0.25);
});
document.getElementById('zoomin').addEventListener('click', function() {
  zoomer.zoom(0.25);
});

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

</script>
Atilt answered 21/7, 2019 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.