计算图像B中图像A的大小

ada*_*ign 5 javascript math jquery

JS问题解决中的一些数学计算

我正在开发一个缩放图像功能,可以创建一个div带有大图像的新图像,该图像根据图像上的鼠标移动通过x和y移动.

大图像应该移动一定的%,这是我想要弄清楚的.它应该移动多少.

这是一些信息:

  • 小图像始终具有相同的大小和正方形.(它实际上总是221px X 221px)
  • 大图像变化(也总是正方形,可以是任何大小,如1000x1000)
  • 缩放器的视口始终相同.

我想计算小图像的大小(或反之亦然).

这是一个完整的大脚本的中间.我开始编写计算公式:再次,我想要的是逐步将百分比转换为像素.首先获取%然后将其转换为像素.

    zoomObj.caluculateSizes = function(){
        $(zoomObj.largeImage).load(function(){
            // zoomObj.callingEvent is the small image
           zoomObj.smlImgSize = zoomObj.callingEvent.width()
           zoomObj.lrgImgSize = zoomObj.largeImage.width()

           // How do i go from here?
    })
Run Code Online (Sandbox Code Playgroud)

js继续.......

roc*_*hal 1

这只是一些简单的数学......

w - width of the small image
W - width of the big image
l - left position of the small image
L - left position of the big image

L = l + 1/2w - 1/2W

h - height of the small image
H - height of the big image
t - top position of the small image
T - top position of the big image

T = t + 1/2h - 1/2H
Run Code Online (Sandbox Code Playgroud)

所以假设我们的图像是:

<img style="width:221px; height:221px; position:absolute; left:600px; top:700px;" />
Run Code Online (Sandbox Code Playgroud)

回答:

Left = 600 + 1/2*221 - 1/2*1000 = 210 (rounded)
Top = 700 + 1/2*221 - 1/2*1000 = 310 (rounded)

<img style="width:1000px; height:1000px; position:absolute; left:210px; top:310px;" />
Run Code Online (Sandbox Code Playgroud)

使用此计算,您可以确定需要将大图像/div 放置在相对于其他对象居中的位置。


编辑:为了将它们放在一起,假设 bigImage 是视口的子项,您需要使用 0 作为 t 和 0 作为 l。

Left = 0 + 1/2*221 - 1/2*1000 = -390 (rounded)
Top = 0 + 1/2*221 - 1/2*1000 = -390 (rounded)

<div id="viewport" style="width:221px; height:221px;overflow:hidden;position:relative;">
    <img id="bigImage" style="width:1000px; height:1000px; position:absolute; left:-390px; top:-390px;" />
</div>
Run Code Online (Sandbox Code Playgroud)

- 正如你所看到的,我使用了负值,所以 bigImage 将隐藏在视口后面,因为。