Search code examples
javascriptcsszooming

How to zoom in an image and center it?


Any Idea how to zoom in a image on particular point using javascript, css ? I am using webkit based browser.

I can zoom by specifying zoom property , like `elem.style.zoom="150%", Main problem is I cannot center the image where I want to zoom. I can get the point where I want to zoom using mouseclick.


Solution

  • As I said in my comment above, I would avoid the zoom css property and stick to just javascript. I managed to throw together the following code which works pretty well for the first click, really all it needs is a little more dynamically (even a word?).

            <html>
                  <head>
                    <script type="text/javascript">
                	  function resizeImg (img)
                	  {
                		var resize = 150; // resize amount in percentage
                		var origH  = 200;  // original image height
                		var origW  = 200; // original image width
                		var mouseX = event.x;
                		var mouseY = event.y;
                		var newH   = origH * (resize / 100) + "px";
                		var newW   = origW * (resize / 100) + "px";
                	
                    	// Set the new width and height
                		img.style.height = newH;
                		img.style.width  = newW;
                		
                		var c = img.parentNode;
                		
                		// Work out the new center
                		c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
                		c.scrollTop  = (mouseY * (resize / 100)) - (newH / 2) / 2;
                	  }
                	</script>
                	<style type="text/css">
                	  #Container {
                	    position:relative;
                	    width:200px;
                        height:200px;
                	    overflow:hidden;
                	  }
                	</style>
                  </head>
                  <body>
                    <div id="Container">
                      <img alt="Click to zoom" onclick="resizeImg(this)" 
                        src="https://picsum.photos/200" />
                    </div>
                  </body>
                </html>

    It works in Google Chrome and IE, not sure about others. Like I said hopefully it will point you in the right direction.