本文实例为大家分享了js+canvas代码雨效果的具体代码,供大家参考,具体内容如下
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
html,body{
height: 100%;
width: 100%;
}
#canvas{
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas')
var c= canvas.getContext('2d')
var cw = canvas.width = window.innerWidth
var ch = canvas.height = window.innerHeight
var str = [1,2,3,4,5,6,7,8,9,0,'q','w','e','r','t','y','u','i','a','c','d','f','g','h','j','l']
var init = function(){
this.x = Math.random()*cw
this.y = 0
this.content1 =Math.random()*15
this.speed = Math.random()*5+20
this.add = function(){
this.y+=this.speed
}
this.reset1 = function(){
this.x= Math.random()*cw
this.y = 0
}
}
//定义一个随机色
var gl = c.createLinearGradient(0, 0, cw, ch);
gl.addColorStop(0, 'red');
gl.addColorStop(.5, 'yellow');
gl.addColorStop(1, 'cyan');
var arr=[]
for(var i=0;i<20;i++){
arr.push(new init())
}
setInterval(function(){
c.fillStyle = 'rgba(0,0,0,0.05)'
c.fillRect(0,0,cw,ch)
//上面的两句是给一个背景,放在计时器里面是为了每运行一次,就重新绘画一次
//用来清空好画布
//1,yong rgba()来表示颜色是为了给一个透明度,新画上去的画布没有完全覆盖
//以前的画布,所以有个渐变的效果
for(var i=0;i<arr.length;i++){
c.fillStyle = gl
c.font = '30px 微软雅黑'
c.fillText(str[i],arr[i].x,arr[i].y)
//让他落到底部再回来
if(arr[i].y>ch-20){
arr[i].reset1()
}
arr[i].add()
}
//
},1000/60)
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。