Can you help me solve a challenge I'm facing? I have a website with a fullsize background image, and I need to attach a div to a specific position on the image while ensuring that it scales in the same way as the background image with the "background-size: cover" property.
I've been able to position the div correctly, but resizing it has proven difficult. Here's what I've tried so far:
http://codepen.io/EmmieBln/pen/YqWaYZ
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 = $('<div>').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);
I thought about calculating a scale value based on the ratios of imageWidth/windowWidth and imageHeight/windowHeight and then using this value for scaling, but I couldn't get it to work...
I would appreciate any help or guidance on this matter.