如何放大图像并居中? [英] How to zoom in an image and center it?

查看:120
本文介绍了如何放大图像并居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法如何使用 javascript css 放大特定点上的图像?我使用基于浏览器的 webkit

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

我可以通过指定缩放属性进行缩放,例如`elem.style.zoom =150%,
主要问题是我无法将图像居中放在我想要缩放的位置。
我可以使用鼠标点击获得我想要缩放的点。

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.

推荐答案

正如我在上面的评论中所说,我会避免使用缩放css属性并坚持使用javascript。我设法将以下代码放在一起,第一次点击效果非常好,真正需要的是动态更多(甚至一个字?)。

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>

适用于Google Chrome和IE,不确定别人。就像我说希望它会指向正确的方向。

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

这篇关于如何放大图像并居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆