Canvas 实现雪花效果
效果图:

思路分析:
1、画背景
2、循环画雪花(引入雪花图片)
3、添加随机(x,y)坐标
4、设置随机大小,添加旋转效果
5、添加动画向下移动(当y轴超出画布时,重新设置y轴坐标为0)
不BB直接上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#canvas{
border: 1px solid #666;
}
</style>
<body>
<canvas id="canvas" width="500px" height="500px"></canvas>
</body>
<script>
var canvas = document.querySelector("#canvas")
var ctx = canvas.getContext("2d")
function Snow(time,size,img){
this.time = time
this.size = size
this.starX = []
this.starY = []
this.sizes = []
this.height = []
this.img = new Image()
this.img.src = img
this.create(this.starX,500)
this.create(this.starY,500)
this.create(this.sizes,20)
this.create(this.height,0)
this.img.onload = ()=>{
this.draw()
}
}
Snow.prototype.create = function(obj,val){
for(let i=0;i<this.size;i++){
obj.push(val*Math.random())
}
}
Snow.prototype.draw = function(){
ctx.clearRect(0,0,500,500)
ctx.fillStyle = "#0097e6"
ctx.fillRect(0,0,500,500)
for(let i=0;i<this.size;i++){
ctx.save()
ctx.translate(this.starX[i],this.starY[i]+this.height[i])
ctx.beginPath()
ctx.fillStyle = "#ffffff"
ctx.rotate(Math.PI/180*this.time)
// ctx.arc(0,0,this.sizes[i],0,2*Math.PI,false)
// console.log(img)
ctx.drawImage(this.img, 0, 0,this.sizes[i],this.sizes[i])
ctx.shadowBlur=10;
ctx.shadowColor = "#fefefe"
ctx.fill()
ctx.restore()
if(this.starY[i]+this.height[i] >= 500){
this.height[i] = 0
this.starY[i] = 0
}else{
this.height[i]+=1
}
if(this.time<360){
this.time+=0.005
}else{
this.time = 0
}
}
requestAnimationFrame(this.draw.bind(this))
}
new Snow(0,100,"雪花.png")
</script>
</html>

浙公网安备 33010602011771号