HTML+JS实现星空背景

📅 2026/8/21 14:27:42
HTML+JS实现星空背景
HTMLJS 实现星空背景查看效果http://deld.vip/article/detail/id/21第一步 html:创建画布canvas并设置 id 为starfield设置 id 是为了后面写 js 方便获取到画布标签!DOCTYPEhtmlhtmllangenheadmetacharsetUTF-8metanameviewportcontentwidthdevice-width, initial-scale1.0titleHtmljs 实现星空背景/title/headbody!--创建画布--canvasidstarfield/canvas/body/html第二步 css:为画布标签设置定位坐标为(0,0)排版z-index: -1保证画布处于最底层作为背景canvas{position:fixed;/*设置定位*/top:0;left:0;z-index:-1;/*使画布基于最低层*/background:#0e1729;/*画布背景色*/}第三步 js:varcanvas;varstars_count;varstars;ini();makeStars();varintervalsetInterval(function(){drawStars();},50);//定时刷新星星数据functionini(){//初始化canvasdocument.getElementById(starfield);canvas.widthwindow.innerWidth;canvas.heightwindow.innerHeight;contextcanvas.getContext(2d);starsArray();//数组存放随机生成的星星数据x,y,大小颜色速度stars_count300;//星星数量clearInterval(interval);}functionmakeStars(){//随机生成星星数据for(vari0;istars_count;i){letxMath.random()*canvas.offsetWidth;letyMath.random()*canvas.offsetHeight;letradiusMath.random()*0.8;letcolorrgba(Math.random()*255,Math.random()*255,Math.random()*255,0.8);letspeedMath.random()*0.5;letarr{x:x,y:y,radius:radius,color:color,speed:speed};//x,y,大小颜色速度stars.push(arr);//随机生成的星星数据存在这里}}functiondrawStars(){//把星星画到画布上context.fillStyle#0e1729;context.fillRect(0,0,canvas.width,canvas.height);for(vari0;istars.length;i){varxstars[i][x]-stars[i][speed];if(x-2*stars[i][radius])xcanvas.width;stars[i][x]x;varystars[i][y];varradiusstars[i][radius];context.beginPath();context.arc(x,y,radius*2,0,2*Math.PI);context.fillStylergba(Math.random()*255,Math.random()*255,Math.random()*255,0.8);context.fill();}}window.onresizefunction(){//窗口大小发生变化时重新随机生成星星数据ini();makeStars();intervalsetInterval(function(){drawStars();},50);}