<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#myCanvas{
background-color: #7ACCC8;
margin: auto;
display: block;
}
#movediv{
position: relative;
left: 0;
100px;
height: 100px;
background-color: #faa;
}
</style>
</head>
<body>
<h2>canvas的下雪效果</h2>
<canvas id="myCanvas" width="800" height="400">
该浏览器不兼容canvas标签!
</canvas>
<img id="imgdom" src="img/snow.png" alt="#" style="display:none;">
</body>
<script>
window.onload = function(){
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var Ary = [];
var canvasImg = document.getElementById('imgdom');
movedarw();
function movedarw(){
setInterval(function(){
var rx = Math.random()*1500-500;
var rxadd = Math.random();
var rwh = Math.random()*20;
var newarc = {
x:rx,
y:-50,
w:1,
h:Math.random()*50+10,
color:"#7ACCC8",
fun:function(){
ctx.beginPath();
ctx.fillStyle = newarc.color;
ctx.drawImage(canvasImg,newarc.x,newarc.y,rwh,rwh);
},
}
Ary.push(newarc);
console.log(Ary);
var set = setInterval(function(){
newarc.y += 1;
newarc.x += rxadd;
if(newarc.y >= 400){
clearInterval(set);
Ary.shift(newarc);
}
},10)
},10);
}
function draw(){
ctx.clearRect(0,0,800,400);
Ary.forEach(function(obj){
obj.fun();
})
requestAnimationFrame(draw);
}
draw();
}
</script>
</html>