Scale element proportional to Background Cover with jQuery
我有一个棘手的问题:
我在工作的网站上有完整背景。
现在,我想将div附加到图像上的某个位置,并且该div的缩放方式与具有" background-size:cover"属性的背景图像的缩放方式相同。
因此,在此示例中,我有一张城市的图片,该图片覆盖了浏览器窗口,并且无论窗口大小如何,我都希望div覆盖一栋特定的建筑物。
我已经设法使div停留在一个位置,但无法使其正确调整大小。到目前为止,我所做的是:
http://codepen.io/EmmieBln/pen/YqWaYZ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | var imageWidth = 1920, imageHeight = 1368, imageAspectRatio = imageWidth / imageHeight, $window = $(window); var hotSpots = [{ 'x': -160, 'y': -20, 'height': 400, 'width': 300 }]; function appendHotSpots() { for (var i = 0; i < hotSpots.length; i++) { var $hotSpot = $('').addClass('hot-spot'); $('.container').append($hotSpot); } positionHotSpots(); } function positionHotSpots() { var windowWidth = $window.width(), windowHeight = $window.height(), windowAspectRatio = windowWidth / windowHeight, $hotSpot = $('.hot-spot'); $hotSpot.each(function(index) { var xPos = hotSpots[index]['x'], yPos = hotSpots[index]['y'], xSize = hotSpots[index]['width'], ySize = hotSpots[index]['height'], desiredLeft = 0, desiredTop = 0; if (windowAspectRatio > imageAspectRatio) { yPos = (yPos / imageHeight) * 100; xPos = (xPos / imageWidth) * 100; xSize = (xSize / imageWidth) * 1000; ySize = (ySize / imageHeight) * 1000; } else { yPos = ((yPos / (windowAspectRatio / imageAspectRatio)) / imageHeight) * 100; xPos = ((xPos / (windowAspectRatio / imageAspectRatio)) / imageWidth) * 100; } $(this).css({ 'margin-top': yPos + '%', 'margin-left': xPos + '%', 'width': xSize + 'px', 'height': ySize + 'px' }); }); } appendHotSpots(); $(window).resize(positionHotSpots); |
我的想法是:
如果(imageWidth / windowWidth)<1,则将var Scale的值设置为(windowWidth / imageWidth),否则将var Scale(windowHeight / imageHeight)设置为
并使用var Scale进行变换:scale(Scale,Scale)
但是我无法做到这一点。||
也许你们可以帮助我解决问题||
背景大小的解决方案:cover
我正在尝试为您提供解决方案(或考虑为一个想法)。您可以在此处查看工作演示。调整窗口大小以查看结果。
首先,我不明白您为什么使用
此处
1 2 3 4 5 6 7 8 9 | var imageWidth = 1920; var imageHeight = 1368; var h = { x: imageWidth / 2, y: imageHeight / 2, height: 100, width: 50 }; var rImage= imageWidth / imageHeight; |
在窗口大小调整处理程序中,计算视口
接下来,技巧是在调整窗口大小时找到图像的尺寸。但是,视口将剪辑图像以保持纵横比。因此,要计算图像尺寸,我们需要一些公式。
使用
1 2 3 | if(actual_image_aspectratio <= viewport_aspectratio) image_width = width_of_viewport image_height = width_ofviewport / actual_image_aspectratio |
和
1 2 3 | if(actual_image_aspectratio > viewport_aspectratio) image_width = height_of_viewport * actual_image_aspectratio image_height = height_of_viewport |
使用
获取图像尺寸后,我们需要绘制从实际图像到新图像尺寸的热点坐标。
为使图像适合视口,图像将被裁剪在顶部
n
n
n
n
n