How to find the center of an image and place another image on top of it?

HTML:

<img src="img/image1.jpg" id = "image1" style="width: 100%;" allign = "center">

JavaScript:

var image1 = document.getElementById("image1");

How do I get the center of this image and then place another image that has an absolute position on top of its blind spot?

+4
source share
3 answers

You can use getBoundingClientRect()in the images to find their exact position and calculate using these values. This method will consider CSS size as well as scroll position, etc.

The second image is placed below using a fixed position for demonstration, but you can use the parent div set to relative, and place the image inside it using absolute, etc.

Example

function centerImages() {
  var image1 = document.getElementById("image1");
  var rect1 = image1.getBoundingClientRect();
  var cx = rect1.left + rect1.width * 0.5;    // find center of first image
  var cy = rect1.top + rect1.height * 0.5;

  var image2 = document.getElementById("image2");
  var rect2 = image2.getBoundingClientRect();
  var x = cx - rect2.width * 0.5;            // use center of first, subtract second
  var y = cy - rect2.height * 0.5;
  image2.style.cssText = "position:fixed;left:" + x + "px; top:" + y + "px";
}
window.onload = window.onresize = window.onscroll = centerImages;
<img src="http://i.stack.imgur.com/UDTPI.gif" id="image1" style="width: 100%;">
<img src="http://i.stack.imgur.com/fk5Js.gif" id="image2">
Run codeHide result
+3

http://jsfiddle.net/33ra14az/1/ JS + resize .

function setImg() {
var img1 = document.getElementById('image1'),
    img2 = document.getElementById('image2'),
    offtop = ((img1.offsetHeight/2)-(img2.offsetHeight/2)),
    offleft = ((img1.offsetWidth/2)-(img2.offsetWidth/2));
    img2.style.top = offtop + "px";
    img2.style.left = offleft + "px";
}
window.load = setImg();
window.addEventListener('resize',setImg);
+2

, :

$(document).ready(function() {

    var top=($("#image1").height()/2)-($("#image2").height()/2);
    var left=($("#image1").width()/2)-($("#image2").width()/2);
    $("#image2").css('left',left+'px');
    $("#image2").css('top',top+'px');
});

and css is simple:

#image2{
    position: absolute;
    display:block;
    width:100px;
    height:100px;
}

and this is the html code:

<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo.png" id = "image1" style="width: 100%;" allign = "center">
    <img src="http://www.hakandemirel.com.tr/blog/wp-content/uploads/jsfiddle.png" id ="image2">

This is a demo: http://jsfiddle.net/yysdged6/22/

+1
source

All Articles