Skip to content Skip to sidebar Skip to footer

How To Add Images One On Another Image Using Javascript

I have small requirement: I need add image over(up) the another image through javascript. Please give me the suggestion! function sampleImage() { document.getElementById(

Solution 1:

You need to enclose the two images in a <div> and then use the following CSS attributes:

div {
    position: relative;
}

​#img2 {
    position: absolute;
    top: 100px;
    left: 100px;
}

See http://jsfiddle.net/C8hh4/

The second image must be a sibling of the first, it cannot be a descendent because that's not legal HTML. The <div> needs to have relative position otherwise #img2's absolute position will be calculated relative to the closest ancestor that doesn't have the default static position.

The value for top should be half of the difference between the outer image's height and the inner image's height, and likewise for the left / width.

If your content is static, calculate those values by hand. If it's dynamic, use JS to set the style:

var img1 = $('#img1')[0];
var img2 = $('#img2')[0];

var top = 0.5 * (img1.height - img2.height);
var left = 0.5 * (img1.width - img2.width);

$(img2).css({top: top, left: left});

Solution 2:

You could use relative positioning. Stack the images on top of each other and set position:relative;top:VALUE; Value should be -HalfHeightOfBackgroundImage-HalfHeightOfForegroundImage.

Another approach whould be wrapping the foreground image in a div and setting the the background image as the background-image.


Solution 3:

Why javascript? Of course, you could use a canvas and paint them over each other, but I would recommend simple CSS:

<img
  style="padding: 20px 7px, background: url('/some/frame.png')"
  src="/cock.jpg"
  width="50px" height="40px"
/>

You might use a class for that, the inline style is just shorter.


Solution 4:

You should do (I saw jquery tag):

$("#img1 img").first().prop("src", "C:\Users\rajasekhark\Desktop\assets\images\Cock.png");

And an advice: DO NOT use full path to your local disk ...


Solution 5:

The jQuery option would be

$("#img1").prop("src","blahblah.jpg");

Although I don't really understand your question.

If you mean that you need to change the image on hover then perhaps this will help...

$("#img1").hover(
    function () {
    $(this).prop("src","newImage.jpg");
    }, 
    function () {
    $(this).prop("src","originalImage.jpg");
});

EDIT:

OK... What you need is a div with the green flashcard as the background image. And place the cock image in that div but set to display:none;

Then on hover just show the image of the cock.

$("#containerDiv").hover(
    function () {
    $(this).find("img").show();
    }, 
    function () {
    $(this).find("img").hide();
});

Post a Comment for "How To Add Images One On Another Image Using Javascript"