【发布时间】:2018-07-01 09:40:36
【问题描述】:
我正在尝试向画布多次添加相同的小图像。它在 Inspect Elements 中正确显示,除了图像有 0x0 像素(自然是 200x45 或其他东西)。
代码如下:
$(document).ready(function(){
var bgd1 = document.getElementById('background1'),
bgd2 = document.getElementById('background2'),
WIDTH,
HEIGHT,
nbgd1,
nbgd2,
bgd1imgs = [];
setBackgroundSize();
drawbgd1();
function setBackgroundSize() {
WIDTH = document.documentElement.clientWidth,
HEIGHT = document.documentElement.clientHeight;
bgd1.setAttribute("width", WIDTH);
bgd1.setAttribute("height", HEIGHT);
bgd2.setAttribute("width", WIDTH);
bgd2.setAttribute("height", HEIGHT);
}
window.addEventListener('resize', setBackgroundSize, false);
function addbgd1(){
this.obj = document.createElement('img');
this.obj.src = 'img/bgd1.png';
this.obj.classList.add('bgd1img');
this.obj.width = 100;
this.obj.height = 22;
this.obj.style.top = Math.floor((window.innerHeight * Math.random())) + 'px';
this.obj.style.left = Math.floor((window.innerWidth * Math.random())) + 'px';
bgd1.appendChild(this.obj);
}
function drawbgd1(){
nbgd1 = Math.floor(WIDTH / 100);
for(var i=0; i<nbgd1 ; i++){
bgd1imgs.push(new addbgd1());
}
}
});
完全迷失在这里。我尝试了几种 CSS 变体,但没有任何区别。
这是 CSS:
#background1{
position:fixed;
z-index:-20;
top:0;
left:0;
background-color:#000;
overflow:hidden;
}
.bgd1img{
z-index:180;
visibility:visible;
display:block;
height:22px;
width:100px;
position:fixed;
}
谢谢!
【问题讨论】:
-
顺便说一句,我正在调用 drawbgd1();
-
请提供一个runnable minimal reproducible example
-
这是完整的
标签: javascript image random background createelement