user3261881 user3261881 - 1 month ago 14
HTML Question

Pure JavaScript Image Grab-Zoom?

In the past I came across http://www.jacklmoore.com/zoom/ which was a great find and very simple to use for a variety of images. I am looking for a grab-zoom feature using pure-javascript rather than jQuery. Is there any Pure-Javascript solution for this? I've attempted this with no luck so far:

Javascript:

var imgSize = 1;
function zoomIn() {
imgSize += 0.1;
document.body.style.imgSize = imgSize + "em";
}
function zoomOut() {
imgSize -= 0.1;
document.body.style.imgSize = imgSize + "em";
}


HTML

<img src="picture.png" value="+" onClick="zoomIn()"/>


Thanks in advance for any helpful tips!

Answer

The general idea is to display the smaller sized image ("original") and when the mouse is hovering over the container, the background image of the container is revealed. The background image is large, and the CSS background is clipped by the container's size. Mouse events are tracked. You'll have to work out the measurement and math yourself.

<div id="imageview" style="position:relative;width:300px;height:200px;"
>
  <img src="300x200.jpg" id="original" onmouseover="this.style.display='none';">

</div>

<script>

  document.getElementById('imageview').onmouseover=function(e){
    document.getElementById('original').style.display='none';
    var x,y;
    if (e) {x=e.clientX;y=e.clientY;} else {x=event.clientX; y=event.clientY;}

    document.getElementById('imageview').orgx=x;
    document.getElementById('imageview').orgy=y;

  }

  document.getElementById('imageview').onmousemove=function(e){
    var x,y;
    if (e) {x=e.clientX;y=e.clientY;} else {x=event.clientX; y=event.clientY;}

    var orgx=document.getElementById('imageview').orgx;
    var orgy=document.getElementById('imageview').orgy;

    //now you have x, y, orgx, and org y, so you can do some math
    // ...

    var posx, posy;

    document.getElementById('imageview').backgroundImage='url(600x400.jpg)';
    document.getElementById('imageview').backgroundPosition=-1*posx+'px '+ -1*posy+'px';


  }

</script>
Comments