Jquery 鼠標吸附粒子動態背景是一種非常有趣的網頁設計效果,它讓網頁的背景動態起來,增添了很多生動活潑的氣息。下面我們來了解一下,如何在網站中添加這種特效。
// HTML結構
<canvas id="canvas"></canvas>
// JS代碼
$(document).ready(function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var mouse = {
x: null,
y: null,
radius: 100
}
window.addEventListener('mousemove', function(event){
mouse.x = event.x;
mouse.y = event.y;
});
window.addEventListener('resize', function(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
var particles = [];
function Particle(x, y, radius){
this.x = x;
this.y = y;
this.radius = radius;
this.color = '#fff';
this.radians = Math.random() * Math.PI * 2;
this.velocity = 0.05;
this.distanceFromCenter = Math.random() * 300 + 50;
this.lastMouse = {x: x, y: y};
this.draw = function(lastPoint){
ctx.beginPath();
ctx.strokeStyle = this.color;
ctx.lineWidth = this.radius;
ctx.moveTo(lastPoint.x, lastPoint.y);
ctx.lineTo(this.x, this.y);
ctx.stroke();
ctx.closePath();
}
this.update = function(){
this.lastMouse.x += (mouse.x - this.lastMouse.x) * 0.05;
this.lastMouse.y += (mouse.y - this.lastMouse.y) * 0.05;
this.radians += this.velocity;
this.x = this.lastMouse.x + Math.cos(this.radians) * this.distanceFromCenter;
this.y = this.lastMouse.y + Math.sin(this.radians) * this.distanceFromCenter;
this.draw(this.lastMouse);
}
}
function init(){
for (var i = 0; i< 50; i++){
var radius = Math.random() * 2 + 1;
particles.push(new Particle(canvas.width/2, canvas.height/2, radius));
}
}
function animate(){
requestAnimationFrame(animate);
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i< particles.length; i++){
particles[i].update();
}
}
init();
animate();
});
以上是添加此特效的代碼,通過鼠標的移動讓粒子發生變化,從而實現了背景的動態效果。對于網頁設計師而言,這種特效為網頁增添了更多的樂趣,讓網站瀏覽的過程變得更加生動有趣。