html 代码片段
- <!DOCTYPE html>
- <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta charset="utf-8" />
- <title>canvas 写下雨效果 </title>
- <style>
- body { background: url(http://pic.qiantucdn.com/58pic/18/25/22/85258PIC5ZN_1024.jpg) #000; background-size: cover; }
- canvas { position: absolute; z-index: 10; top: 0; left: 0; opacity: 0.5; }
- </style>
- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
- <script type="text/javascript">
- $(function () {
- var W = $(window).width(),
- H = $(window).height(),
- x2 = -15, len = 30, count = 100;
- var canvas = document.getElementById("snow");
- canvas.width = W;
- canvas.height = H;
- var ctx = canvas.getContext('2d');
- setInterval(clearCanvas,100);
- function clearCanvas() {
- ctx.clearRect(0, 0, W, H);
- draws();
- }
- function draw(x, y) {
- //canvas 写渐变: createLinearGradient(startX,startY,endX,endY)
- var grd = ctx.createLinearGradient(x, y, x + x2, y + len);
- grd.addColorStop(0, "rgba(0,0,0,0)");
- grd.addColorStop(0.5, "rgba(105,105,105,1)");
- grd.addColorStop(1, "rgba(255,255,255,1)");
- ctx.strokeStyle = grd;
- ctx.beginPath();
- ctx.moveTo(x, y);
- ctx.lineTo(x + x2, y + len);
- ctx.lineWidth = 2;
- ctx.stroke();
- ctx.closePath();
- }
- function draws() {
- for (var i = 1; i <= count; i++) {
- console.log(i)
- draw(Math.random() * W, Math.random() * H);
- }
- }
- });
- </script>
- </head>
- <body>
- <canvas id="snow"> 不支持 canvas</canvas>
- </body>
- </html>
来源: http://www.qdfuns.com/article/14864/cc9c097c9cc8eae24e7c7b08c05b8622.html