<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./css/opp.css">
<style>
*{
margin: 0;
padding: 0;
}
html,body{
background-color: #f2f2f2;
height:2000px;
overflow: auto;
}
canvas{
background-color: #fff;
position: fixed;
top: 0;
left: 0;
}
</style>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<script>
//获取屏幕宽高
var width = window.innerWidth,height=window.innerHeight;
// 添加canvas元素
document.write('<canvas id="canvas" width="'+window.innerWidth+'" height="'+window.innerHeight+'"></canvas>');
$(function(){
// boll构造函数,(位置、每次刷新的位移、半径)
function Boll(x,y,dx,dy,r){
this.x=x;
this.y=y;
this.dx=dx;
this.odx=dx;
this.dy=dy;
this.ody=dy;
this.r= r;
this.or= r;
this.bg = '#'+((Math.random()*255).toFixed(0)*1).toString(16)+((Math.random()*255).toFixed(0)*1).toString(16)+((Math.random()*255).toFixed(0)*1).toString(16);//随机颜色
}
// boll画入
Boll.prototype.draw=function(r){
ctx.beginPath();
ctx.fillStyle = this.bg;
ctx.arc(this.x,this.y,this.r,Math.PI/180*0,Math.PI/180*360,false);
ctx.fill();
};
// 位移
Boll.prototype.update=function(){
if(this.x<0||this.x>width){
this.dx=-this.dx;
this.odx = this.dx;
}
if(this.y<0||this.y>height){
this.dy = -this.dy;
this.ody = this.dy;
}
this.x+=this.dx;
this.y+=this.dy;
if(mouse.x+yxs>this.x&&mouse.x<(this.x+yxs)&&mouse.y+yxs>this.y&&mouse.y<(this.y+yxs)){
this.dx=(-this.x+mouse.x)*0.1;
this.dy=(-this.y+mouse.y)*0.1;
}else{
this.dx=this.odx;
this.dy=this.ody;
}
if(mouse.x+s+this.r>this.x&&mouse.x<(this.x+s+this.r)&&mouse.y+s+this.r>this.y&&mouse.y<(this.y+s+this.r)){
if(this.r<30){
this.r++;
}
}else{
this.r= --this.r<=this.or?this.or:this.r;
}
this.draw();
};
var canvas = $('#canvas')[0],
ctx = canvas.getContext('2d'),
arr=[],//boll数组
num = 1000,//boll数量
mouse={x:0,y:0},//鼠标位置
yxs=50,//可吸引boll的区域范围
s=10;//可使boll变大的区域范围
// 监听鼠标位置
window.addEventListener('mousemove',function(e){
mouse.x=e.clientX;
mouse.y=e.clientY;
})
// 实例化num个boll
for(var i=0;i<num;i++){
arr.push(new Boll(Math.random()*width,Math.random()*height,(Math.random()-0.5)*2,(Math.random()-0.5)*2,returnNum(2,4)));
}
// 实现动画,先清空画布,再把位移的num个boll画上去
function ani(){
ctx.beginPath();
ctx.fillStyle='#fff';
ctx.fillRect(0,0,width,height);
for(var i=0;i<num;i++){
arr[i].update();
}
requestAnimationFrame(ani);
}
ani();
// 得到a,b范围内的数
function returnNum(a,b){
return Math.random()*(b-a)+a;
}
})
</script>
</body>
</html>
canvas(多色小球) 网页交互背景效果小demo
最新推荐文章于 2024-05-28 09:48:51 发布