Spawn a image on another image giving a coordinate

核能气质少年 提交于 2020-06-16 06:04:14

问题


I have some image coordinates and I want to use them to put a small image on those with javascript. Can this be accomplished with javascript or I need to create the div and modify it's css attributes? By the way: the image can be placed anywhere on the page.


回答1:


Here is a fully working code: Live Demo

CSS

.overlays{
    position:absolute;
}

JS

function showImage() {
    // myImage : ID of image on which to place new image

    var image = document.getElementById('myImage');

    console.log(image.width);

    margin = 20;

    l = image.offsetLeft;
    t = image.offsetTop;
    w = image.width;
    h = image.height;

    // Location inside the image
    offX = parseInt(Math.random() * w);
    offY = parseInt(Math.random() * h);

    if(offX > margin) offX -= margin;
    if(offY > margin) offY -= margin;

    l += offX;
    t += offY;

    var newImage = document.createElement("img");
    newImage.setAttribute('src', '1.jpg');
    newImage.setAttribute('class', 'overlays');
    newImage.style.left = l + "px";
    newImage.style.top = t + "px";
    document.body.appendChild(newImage);
}



回答2:


css:

#yourId{
    position: absolute;
}

js:

var img = document.getElementById('yourId'), // or any other selector
    x = x, // your data
    y = y; // your data
img.style.left = x+"px";
img.style.top = y+"px";



回答3:


Try this to place the new image on coordinates (X,Y) of a parent image:

var newImg = document.getElementById('newImg'), // your new (small) image
    img = document.getElementById('parentImg'); // parent image
document.body.insertBefore(newImg, img); // Insert the new image before the image
document.body.insertBefore(img, newImg); // Then switch places (So the small image is after the big one in the DOM)

newImg.style.position = 'relative';
newImg.style.left = X + "px";
newImg.style.top = (Y - img.height)+"px"; // Substract the height of the source image to get the position relative to the top left.

The double insertBefore is to insert the new image after the bid one, by first inserting it before the big one, then moving the big one in front of it.
Then, it's just a matter of setting the new image's coordinates relative to the big image.

Working Example (Set to display the overlay after 2 seconds to show the difference)



来源:https://stackoverflow.com/questions/14157790/spawn-a-image-on-another-image-giving-a-coordinate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!