canvas下雨特效

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas下雨特效</title>
</head>

<body>
<canvas id='mycanvas'></canvas>
</body>
<script>
/**
* 定义从黑到白的渐变(从左向右),作为矩形的填充样式:createLinearGradient(左,上,右,下)
* addColorStop(1,开始颜色) (0,结束颜色)
* strokeStyle 设置或返回用于笔触的颜色、渐变或模式
* shadowColor 设置或返回用于阴影的颜色
* shadowBlur 设置或返回用于阴影的模糊级别
* shadowOffsetX 设置或返回阴影距形状的水平距离 大于0往右边走
* shadowOffsetY 设置或返回阴影距形状的垂直距离 大于0往下走
* fillStyle 填充画布
*
* createLinearGradient() 创建线性渐变(用在画布内容上)
* createPattern() 在指定的方向上重复指定的元素
* createRadialGradient() 创建放射状/环形的渐变(用在画布内容上)
* addColorStop() 规定渐变对象中的颜色和停止位置
* document.body.clientWitdth 可视宽高
*
* canvas 线条属性
* ctx.beginPath();//开始使用线条
* lineWidth=5 线条宽度
lineCap="butt"; 属性设置 或者返回线条末端线帽样式
butt 默认。向线条的每个末端添加平直的边缘。
round 向线条的每个末端添加圆形线帽
square 向线条的每个末端添加正方形线帽

lineJoin 当两条线条交汇时,创建圆形边角:
bevel 创建斜角
round 创建圆角
miter 默认。创建尖角。

lineWidth 线条宽度
miterLimit 设置或返回最大斜接长度

矩形
rect 创建矩形
fillRect 填充矩形
strokeRect() 绘制矩形(无填充)
clearRect() 在给定的矩形内清除指定的像素
*
*
*/
(function(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var w = document.documentElement.offsetWidth;
var h = document.documentElement.offsetHeight;
var x = 0, y = 0,len = 10,angle = -2,count = 100;
var rainTimer = null,drawTimer = null;

//线条颜色
var color = ctx.createLinearGradient(0,0,0,len);
color.addColorStop(0,'red');
color.addColorStop(1,'rgba(255,255,255,0.2)');
console.log(color);
//ctx.strokeStyle = 'rgba(255,255,255,0.2)';
ctx.strokeStyle = color;

function drawRain(x,y)
{
//每次绘制渐变线条 都需要找到坐标
var color = ctx.createLinearGradient(x,y,x+angle,y+len);
//color.addColorStop(0,'rgba(254,139,199,0.3)');
color.addColorStop(0,'rgba(0,0,0,0.1');
color.addColorStop(1,'rgba(255,255,255,0.2)');
ctx.strokeStyle = color;

ctx.beginPath()
ctx.moveTo(x,y);
ctx.lineWidth=1;
ctx.lineTo(x + angle,y+len);
ctx.stroke();

}


//绘制满屏的雨滴
function fullWindowRain()
{
var i = 0;
for(i = 0;i < count; i++)
{
drawRain(w*Math.random(),h*Math.random());
}
}

//改变大雨或者小雨
function changeRain()
{
rainTimer = setInterval(function(){
count = Math.ceil(500 + 100 * Math.random());
},2000);
}

changeRain();
reDraw();

//重绘的频率
function reDraw()
{
drawTimer = setInterval(function(){
ctx.clearRect(0,0,w,h+200);
fullWindowRain();
},100);
}
})();
</script>
</html>
原文地址:https://www.cnblogs.com/930115586qq/p/9488929.html