效果?:

直接在你的頁面參考方法?:
1.新建一個名為 canvasStar.js的檔案:

2.右鍵打開該 js 檔案,把下面代碼復制進去:
window.addEventListener('load',()=>{
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
window.onresize=resizeCanvas;
function resizeCanvas(){
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
}
resizeCanvas();
canvas.style.cssText = `
position: fixed;
z-index: 1000;
pointer-events: none;
`
//
var arr = [];
var colours =["#ffff00","#66ffff","#3399ff","#99ff00","#ff9900"];
//
window.addEventListener('mousemove', e=>{
arr.push({
x:e.clientX,
y:e.clientY,
r:Math.random()*0.5+1.5,
td:Math.random()*4-2,
dx:Math.random()*2-1,
dy:Math.random()*1+1,
rot: Math.random()*90+90,
color: colours[Math.floor(Math.random()*colours.length)]
});
})
//
function star(x,y,r,l,rot){
ctx.beginPath();
for(let i=0;i<5;i++){
ctx.lineTo(Math.cos((18 + i*72 -rot)*Math.PI/180)*r+x,
-Math.sin((18 + i*72 - rot)*Math.PI/180)*r+y);
ctx.lineTo(Math.cos((54+i*72-rot)*Math.PI/180)*l+x
,-Math.sin((54+i*72 -rot)*Math.PI/180)*l+y);
}
ctx.closePath();
}
//
function draw(){
for(let i=0;i<arr.length;i++){
let temp = arr[i];
star(temp.x,temp.y,temp.r,temp.r*3,temp.rot);
ctx.fillStyle = temp.color;
ctx.strokeStyle = temp.color;
ctx.lineWidth = 0.1;
ctx.lineJoin = "round";
ctx.fill();
ctx.stroke();
}
}
//
function update(){
for(let i=0;i<arr.length;i++){
arr[i].x += arr[i].dx;
arr[i].y += arr[i].dy;
arr[i].rot += arr[i].td;
arr[i].r -= 0.015;
if(arr[i].r<0){
arr.splice(i,1);
}
}
}
setInterval(()=>{
ctx.clearRect(0,0,canvas.width,canvas.height);
draw();
update();
},20)
})
3. 在你想要的顯示效果的頁面插入該js檔案:
如在這引入,src寫上檔案在的路徑:

4.在body里添該加標簽:
<canvas id="canvas"></canvas>
如:

以上就完成了~
總結:
這樣在你的網頁就可以直接看到跟隨滑鼠移動的小星星效果了,如果需要解釋代碼意思和制作程序的留言,我可以下次出篇文章詳細說說怎么做~

其它文章:
環繞倒影加載特效 html+css
氣泡浮動背景特效 html+css
簡約時鐘特效 html+css+js
賽博朋克風格按鈕 html+css
仿網易云官網輪播圖 html+css+js
水波加載影片 html+css
導航欄滾動漸變效果 html+css+js
書本翻頁 html+css
3D立體相冊 html+css
霓虹燈繪畫板效果 html+css+js
記一些css屬性總結(一)
Sass總結筆記
…等
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/279819.html
標籤:其他
上一篇:前端js遍歷總結。。。
