平时看到不错的冬景照片想收藏起来,如果将其添加上飘雪的效果,更加美不胜收,比如下面效果
下面分享一下如果利用canvas为图片添加飘雪效果,先看代码,再分析;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> canvas { border:1px solid red; /*添加背景图片*/ background: url(img/snow.jpg); } </style> </head> <body> <canvas id="can" width="800" height="600"></canvas> <script type="text/javascript"> var can = document.getElementById("can"); var ctx = can.getContext("2d"); //定义一个随机函数 function random(min,max){ return parseInt(Math.random()*(max-min)+min); } //创建一个动画类 function AnimationClass(){ //雪花出现的坐标 this.x = random(0,can.width);//横坐标随机 this.y = 0;//纵坐标为0 this.radius = random(1,5);//雪花的半径随机 this.color = "white";//颜色红色 this.speed = random(1,6);//雪花降落的速度随机 this.startAngle = 0;//起始角度 this.endAngle = Math.PI*2;//终止角度 } //给雪花动画类添加一个方法 AnimationClass.prototype.draw = function(){ ctx.save();//储存 ctx.fillStyle = this.color;//填充颜色 //绘制雪花 ctx.beginPath(); ctx.arc(this.x,this.y,this.radius,this.startAngle,this.endAngle);//画圆 ctx.fill(); ctx.restore(); this.sport();//调用运动函数使雪花运动起来 }; //雪花运动原型方法 AnimationClass.prototype.sport = function(){ this.y += this.speed;//雪花y方向上的值累加 }; //创建一个雪花对象 var dataArr =[]; function show(){ can.height = can.height;//清除画布内容 var A = new AnimationClass();//创建一个雪花动画A dataArr.push(A);//将创建的雪花动画储存在数组dataArr中 //调用创建的数组中雪花对象方法 for (var i in dataArr){ dataArr[i].draw(); } requestAnimationFrame(show);//循环调用 } show(); </script> </body> </html>
主要思路分析:
1)首先将背景图片置入画布背景中
2)考虑到雪花的大小和运动速度都是随机的,所以构造一个随机函数random
3)创建一堆雪花之前先创建出一个雪花类,然后对这一个雪花不断调用就可以得到很多雪花飘落的特效。
利用面向对象的思路分析一个雪花类具备的属性和方法,属性有雪花的起始位置(画布顶端),雪花颜色(白色),终止位置(画布底部),随机速度范围,绘制学画圆形的起止角度。雪花类有两个原型方法,一个是画出雪花形状的方法draw,另一个是运动方法sports,画出来的这个雪花运动才有效果,所以画出雪花后就调用sposts函数使其具备运动“性能”。
4)这样雪花的属性和方法由雪花类创建出来了,由于需要很多个雪花,就将创建的雪花实例放在数组中,然后调用雪花类的方法,将这些代码封装在一个show函数中,在里面用requestAnimationFrame不断自我调用,实现众多雪花的效果。