Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...