![](/img/trans.png)
[英]How to calculate the distance between the top-left corner of an HTML element and the window top-left corner?
[英]Randomly moving images are attracted by the top-left corner of the screen
我正在嘗試制作在屏幕上隨機移動的圖像。
圖像在屏幕上隨機定位,然后每10ms從-15px移動到15px。
但幾秒鍾后,圖像會集中在屏幕的左上角,而不是分散在整個屏幕上(或者至少集中在屏幕的另一個角落)......
您可以在此處查看我的代碼: http : //secretlabs.alwaysdata.net/bug.html
window.onload = function() {
var imgUrl = 'http://image.jeuxvideo.com/smileys_img/18.gif';
var imgs = [];
var imgPos = [];
for(var i = 0; i < 50; i++) {
// Create 50 images.
imgs.push(new Image());
imgs[i].src = imgUrl;
imgs[i].style.position = 'absolute';
// Position them randomly on the screen.
imgPos[i] = [Math.floor(Math.random() * window.innerWidth),
Math.floor(Math.random() * window.innerHeight)];
imgs[i].style.left = imgPos[i][0] + 'px';
imgs[i].style.top = imgPos[i][1] + 'px';
document.body.appendChild(imgs[i]);
}
window.setInterval(function() {
for(var i = 0; i < 50; i++) {
// Move randomly each image from -15px to 15px, vertically and horizontally.
imgPos[i][0] += Math.floor(Math.random() * 30) - 15;
imgPos[i][1] += Math.floor(Math.random() * 30) - 15;
// Avoid images to go out of the screen.
if(imgPos[i][0] < 0)
imgPos[i][0] = 0;
if(imgPos[i][1] < 0)
imgPos[i][1] = 0;
if(imgPos[i][0] > window.innerWidth - 16)
imgPos[i][0] = window.innerWidth - 16;
if(imgPos[i][1] > window.innerHeight - 16)
imgPos[i][1] = window.innerHeight - 16;
imgs[i].style.left = imgPos[i][0] + 'px';
imgs[i].style.top = imgPos[i][1] + 'px';
}
}, 10);
};
如果你想要更少偏見的東西,不要向負值舍入。
更換
Math.floor(Math.random() * 30) - 15
同
Math.round(Math.random() * 30 - 15)
我剛用這段代碼做了一個小測試:
var N = 1000000;
for (var j=0; j<20; j++) {
var sum = 0;
for (var i=N; i-->0;) sum += Math.round(Math.random() * 30 - 15);
console.log(sum/N);
}
好像可以 (打開控制台)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.