我有一些图像坐标,我想用它们在带有 javascript 的图像上放置一个小图像。这可以用javascript完成还是我需要创建div并修改它的css属性?顺便说一句:图像可以放在页面上的任何位置。
问问题
3631 次
3 回答
1
这是一个完整的工作代码: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);
}
于 2013-01-04T13:18:04.107 回答
1
试试这个把新图像放在(X,Y)
父图像的坐标上:
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.
双重insertBefore
是在投标后插入新图像,首先将其插入大图像之前,然后将大图像移动到它前面。
然后,只需设置新图像相对于大图像的坐标即可。
工作示例(设置为在 2 秒后显示覆盖以显示差异)
于 2013-01-04T13:20:12.627 回答
0
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";
于 2013-01-04T13:11:36.423 回答