Home > Web Front-end > JS Tutorial > Sharing examples of how to implement rain animation in Canvas

Sharing examples of how to implement rain animation in Canvas

小云云
Release: 2018-03-09 10:49:42
Original
1990 people have browsed it

I saw a rain effect animation made by Canvas on codepen, which was quite interesting. I did some research and here I will share the implementation techniques.

Effect screenshot:

Canvas animation basics

Everyone You know, Canvas is actually just a drawing board. We can use the canvas API to draw various graphics on it.

Canvas 2D API: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D

Then the steps for Canvas drawing animation are:

  1. Draw the first frame of graphics (using API drawing)

  2. Clear the drawing board (apply clearRect() or fillRect())

  3. Draw the next frame of animation

What is used to control the drawing time of each frame of animation? It is easy for everyone to think of window.setInterval() and window.setTimeout(). Yes, you can use these two too. In addition, a new method later appeared: window.requestAnimationFrame(callback).

requestAnimationFrame will tell the browser that you want to draw an animation. Let the browser call your specified method (callback) to draw your animation when it wants to redraw.

The usage method is as follows:


function anim() {
    ctx.fillStyle = clearColor;
    ctx.fillRect(0,0,w,h);
    for(var i in drops){
        drops[i].draw();
    }
    requestAnimationFrame(anim);
}
Copy after login

Generally, priority is given to using requestAnimationFrame to keep the frequency of animation drawing consistent with the frequency of browser redrawing. Unfortunately the compatibility of requestAnimationFrame is not very good yet. IE9 and below and addroid 4.3 and below do not seem to support this attribute. Browsers that do not support it must use setInterval or setTimeout for compatibility.

Raindrop falling effect

First let’s talk about how to create the raindrop falling effect. The raindrop is actually a rectangle, and then the afterimage is added. The drawing of afterimages can be said to be the key to the whereabouts of raindrops. The afterimage is an effect produced by drawing a translucent background and a rectangle every frame in the forward direction, and then superimposing the previously drawn graphics. Since the graphics in the forward direction are drawn last, they appear brighter, and the graphics in the back are superimposed more, so they are visually weakened. The whole thing looks like an afterimage. The key here is to draw a transparent background, otherwise the overlay effect will not be produced.

Let’s draw a raindrop. First prepare a drawing board:

html code:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>霓虹雨</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <style type="text/css">
        .bg {
            background: #000;
            overflow: hidden;
        }
    </style>

</head>
<body class="bg">
<canvas id="canvas-club"></canvas>
<script type="text/javascript" src="raindrop.js"></script>
</body>
</html>
Copy after login

I draw the animation (raindrop.js) in the js file, the code is as follows:


var c = document.getElementById("canvas-club");
var ctx = c.getContext("2d");//获取canvas上下文
var w = c.width = window.innerWidth;
var h = c.height = window.innerHeight;//设置canvas宽、高
var clearColor = &#39;rgba(0, 0, 0, .1)&#39;;//画板背景,注意最后的透明度0.1 这是产生叠加效果的基础

function random(min, max) {
    return Math.random() * (max - min) + min;
}

function RainDrop(){}
//雨滴对象 这是绘制雨滴动画的关键
RainDrop.prototype = {
    init:function(){
        this.x =  random(0, w);//雨滴的位置x
        this.y = 0;//雨滴的位置y
        this.color = &#39;hsl(180, 100%, 50%)&#39;;//雨滴颜色 长方形的填充色
        this.vy = random(4, 5);//雨滴下落速度
        this.hit = random(h * .8, h * .9);//下落的最大值
        this.size = 2;//长方形宽度
    },
    draw:function(){
        if (this.y < this.hit) {
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x, this.y, this.size, this.size * 5);//绘制长方形,通过多次叠加长方形,形成雨滴下落效果
        }
        this.update();//更新位置
    },
    update:function(){
        if(this.y < this.hit){
            this.y += this.vy;//未达到底部,增加雨滴y坐标
        }else{
            this.init();
        }
    }
};

function resize(){
    w = c.width = window.innerWidth;
    h = c.height = window.innerHeight;
}

//初始化一个雨滴
var r = new RainDrop();
r.init();

function anim() {
    ctx.fillStyle = clearColor;//每一帧都填充背景色
    ctx.fillRect(0,0,w,h);//填充背景色,注意不要用clearRect,否则会清空前面的雨滴,导致不能产生叠加的效果
    r.draw();//绘制雨滴
    requestAnimationFrame(anim);//控制动画帧
}

window.addEventListener("resize", resize);
//启动动画
anim();
Copy after login

Ripple effect

Next, draw the ripple effect. Similar to the way of drawing raindrops, the effect of inner shadow is also produced by superimposing the previous image with a transparent background.

The code is as follows (rippling.js):


var c = document.getElementById("canvas-club");
var ctx = c.getContext("2d");//获取canvas上下文
var w = c.width = window.innerWidth;
var h = c.height = window.innerHeight;//设置canvas宽、高
var clearColor = &#39;rgba(0, 0, 0, .1)&#39;;//画板背景,注意最后的透明度0.1 这是产生叠加效果的基础

function random(min, max) {
    return Math.random() * (max - min) + min;
}

function Rippling(){}
//涟漪对象 这是涟漪动画的主要部分
Rippling.prototype = {
    init:function(){
        this.x = random(0,w);//涟漪x坐标
        this.y = random(h * .8, h * .9);//涟漪y坐标
        this.w = 2;//椭圆形涟漪宽
        this.h = 1;//椭圆涟漪高
        this.vw = 3;//宽度增长速度
        this.vh = 1;//高度增长速度
        this.a = 1;//透明度
        this.va = .96;//涟漪消失的渐变速度
    },
    draw:function(){
        ctx.beginPath();
        ctx.moveTo(this.x, this.y - this.h / 2);
        //绘制右弧线
        ctx.bezierCurveTo(
            this.x + this.w / 2, this.y - this.h / 2,
            this.x + this.w / 2, this.y + this.h / 2,
            this.x, this.y + this.h / 2);
        //绘制左弧线
        ctx.bezierCurveTo(
            this.x - this.w / 2, this.y + this.h / 2,
            this.x - this.w / 2, this.y - this.h / 2,
            this.x, this.y - this.h / 2);
        
        ctx.strokeStyle = &#39;hsla(180, 100%, 50%, &#39;+this.a+&#39;)&#39;;
        ctx.stroke();
        ctx.closePath();
        this.update();//更新坐标
    },
    update:function(){
        if(this.a > .03){
            this.w += this.vw;//宽度增长
            this.h += this.vh;//高度增长
            if(this.w > 100){
                this.a *= this.va;//当宽度超过100,涟漪逐渐变淡消失
                this.vw *= .98;//宽度增长变缓慢
                this.vh *= .98;//高度增长变缓慢
            }
        } else {
            this.init();
        }

    }
};

function resize(){
    w = c.width = window.innerWidth;
    h = c.height = window.innerHeight;
}

//初始化一个涟漪
var r = new Rippling();
r.init();

function anim() {
    ctx.fillStyle = clearColor;
    ctx.fillRect(0,0,w,h);
    r.draw();
    requestAnimationFrame(anim);
}

window.addEventListener("resize", resize);
//启动动画
anim();
Copy after login

Summary

This way everyone can understand the entire rain effect You should have a certain understanding of the production method. The effect of Canvas used to draw animations is indeed eye-catching and greatly improves the visual effect of the web. Use your own wisdom and I believe you can make more wonderful animations. This is one of the reasons why I like the web more and more O(∩_∩)O~~.

Related recommendations:

Telling about Canvas combined with JavaScript to achieve picture special effects

HTML5 Canvas interactive subway map implementation code

How to use Canvas to process images

The above is the detailed content of Sharing examples of how to implement rain animation in Canvas. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template