2013-01-04 36 views
2

我有一些圖像座標,我想用它們在javascript上放一個小圖像。這可以用JavaScript來完成,或者我需要創建div並修改它的css屬性?順便說一句:圖像可以放在頁面的任何位置。在給出座標的另一個圖像上產生圖像

+0

用JavaScript您可以創建任何你需要的DOM元素,也改變風格 –

+0

沒錯,但如何改變風格的地方它在一個不固定的圖像的確切座標上? – Octavian

+0

您想要在屏幕上放置任何想要的圖像,這意味着您必須將位置設置爲絕對位置。然後,您可以根據「頂部」,「左側」,「右側」,「底部」定義其位置。 –

回答

0

這裏是一個完全工作代碼: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); 
} 
+0

永遠不要在變量名中使用減號('-')!這是無效的JS('SyntaxError:Unexpected token -'),更不用說使它更難以閱讀。 – Cerbrus

+0

如何計算純JS中的off-x和off-y? (圖像的位置是相對的,我可以說,隨機) – Octavian

+0

@Octavian使用rand()來隨機x,y。 – ATOzTOA

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"; 
0

嘗試使用此方法將新的圖像上的父圖像的座標(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是買入一個後插入新的圖像,首先插入它在大牌之前,然後在它前面移動大牌。
然後,這只是設置新圖像的座標相對於大圖像的問題。

Working Example(設置2秒後,顯示覆蓋以示區別)

相關問題