JavaScript缩放图像和中心可视区域 [英] JavaScript zoom image and center viewable area

查看:107
本文介绍了JavaScript缩放图像和中心可视区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在单击按钮时创建可缩放图像,但是图像应该在可视区域上居中放大,因为图像可能比容器大。

I'm trying to create a zoom able image upon click of a button, however the image should be zoomed centered on the view able area, as the image may be bigger than the container.

我在这里创建了一个小提琴来说明我想要的东西,我显然通常会将图像隐藏在容器外面,我现在不会对这个部分感到困扰,也会放入边框覆盖到显示容器的边界。

I've created a fiddle here to illustrate what I want, I'd obviously usually hide the image outside the container, I'm not bothered about that part just now, also put in a border overlay to show the bounds of the container.

我根据图像比例完成了缩放部分,我只需要计算新的顶部和左侧css值并应用它缩放后的图像。此外,图像是可拖动的,因此一旦移动图像,它必须考虑图像的位置。

I've done the zoom part based on the image ratio, I just need to work out the new top and left css values and apply it to the image after the zoom. Also the image is draggable, so once you move the image it must take into account the position of the image.

基本上,红色容器内图像的中心点缩放后必须保持不变,因此您可以有效地放大容器中间的任何内容。

Basically, the centrol point of the image within the red container must remain the same after the zoom, so you are effectly zooming in on whatever is at the middle of the container.

http://jsfiddle.net/wFaFg/1/

why do you we need code to link to jsfiddle?

谢谢

编辑:

http://jsfiddle.net/FU55w/

与上述小提琴接近,但仍未完全缩放中心点

getting close with the above fiddle, but still not zooming completely on central point

推荐答案

所以我找到了解决方案,

So I found the solution,

这比查看图片大小增加的程度要复杂一些。

It is slightly more complex than just finding out how much the image increased in size.

我计算出x& y容器内图像中心点的y值,取左边和上边的值,将其变为正值,然后加上容器宽度和高度的一半。

I work out the x & y value of the center point of the image within the container, by taking the left and top value, turning it positive then adding half the container width and height.

var x = Math.abs(image.position().left) + container.width() / 2
var y = Math.abs(image.position().top) + container.height() / 2

我通过除以新宽度计算出图像比例的比例按旧宽度,然后我可以乘以x& y按比率计算的值。

I work out the ratio of the image scale by dividing the new width by the old width, then I can multiply the x & y value by the ratio.

然后取消当前左边和顶部的新x和y之间的差值。

Then take the difference between the new x and y away from the current left and top.

image.position().left - (newX - x)
image.position().top - (newY - y)

完整小提琴:
http://jsfiddle.net/phHqQ/

这篇关于JavaScript缩放图像和中心可视区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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