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

Mar 09, 2018 am 10:49 AM
canvas rain animation

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CSS Animation: How to Achieve the Flash Effect of Elements CSS Animation: How to Achieve the Flash Effect of Elements Nov 21, 2023 am 10:56 AM

CSS animation: How to achieve the flash effect of elements, specific code examples are needed. In web design, animation effects can sometimes bring a good user experience to the page. The glitter effect is a common animation effect that can make elements more eye-catching. The following will introduce how to use CSS to achieve the flash effect of elements. 1. Basic implementation of flash First, we need to use the animation property of CSS to achieve the flash effect. The value of the animation attribute needs to specify the animation name, animation execution time, and animation delay time

Animation not working in PowerPoint [Fixed] Animation not working in PowerPoint [Fixed] Feb 19, 2024 am 11:12 AM

Are you trying to create a presentation but can't add animation? If animations are not working in PowerPoint on your Windows PC, then this article will help you. This is a common problem that many people complain about. For example, animations may stop working during presentations in Microsoft Teams or during screen recordings. In this guide, we will explore various troubleshooting techniques to help you fix animations not working in PowerPoint on Windows. Why aren't my PowerPoint animations working? We have noticed that some possible reasons that may cause the animation in PowerPoint not working issue on Windows are as follows: Due to personal

How to set up ppt animation to enter first and then exit How to set up ppt animation to enter first and then exit Mar 20, 2024 am 09:30 AM

We often use ppt in our daily work, so are you familiar with every operating function in ppt? For example: How to set animation effects in ppt, how to set switching effects, and what is the effect duration of each animation? Can each slide play automatically, enter and then exit the ppt animation, etc. In this issue, I will first share with you the specific steps of entering and then exiting the ppt animation. It is below. Friends, come and take a look. Look! 1. First, we open ppt on the computer, click outside the text box to select the text box (as shown in the red circle in the figure below). 2. Then, click [Animation] in the menu bar and select the [Erase] effect (as shown in the red circle in the figure). 3. Next, click [

After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 After a two-year delay, the domestic 3D animated film 'Er Lang Shen: The Deep Sea Dragon' is scheduled to be released on July 13 Jan 26, 2024 am 09:42 AM

This website reported on January 26 that the domestic 3D animated film "Er Lang Shen: The Deep Sea Dragon" released a set of latest stills and officially announced that it will be released on July 13. It is understood that "Er Lang Shen: The Deep Sea Dragon" is produced by Mihuxing (Beijing) Animation Co., Ltd., Horgos Zhonghe Qiancheng Film Co., Ltd., Zhejiang Hengdian Film Co., Ltd., Zhejiang Gongying Film Co., Ltd., Chengdu The animated film produced by Tianhuo Technology Co., Ltd. and Huawen Image (Beijing) Film Co., Ltd. and directed by Wang Jun was originally scheduled to be released in mainland China on July 22, 2022. Synopsis of the plot of this site: After the Battle of the Conferred Gods, Jiang Ziya took the "Conferred Gods List" to divide the gods, and then the Conferred Gods List was sealed by the Heavenly Court under the deep sea of ​​Kyushu Secret Realm. In fact, in addition to conferring divine positions, there are also many powerful evil spirits sealed in the Conferred Gods List.

The final trailer for Netflix's claymation film 'Chicken Run 2” has been announced and will be released on December 15 The final trailer for Netflix's claymation film 'Chicken Run 2” has been announced and will be released on December 15 Nov 20, 2023 pm 01:21 PM

The final trailer for Netflix's claymation film "Chicken Run 2" has been released. The film is expected to be released on December 15. This site noticed that the trailer for "Chicken Run 2" shows Chicken Loki and King Kong. Jay launches an operation to find his daughter Molly. Molly is taken away by a truck at FunLand Farm, and Rocky and Ginger risk their lives to retrieve their daughter. The film is directed by Sam Fehr and stars Sandy Way Newton, Zachary Levi, Bella Ramsey, Imelda Staunton and David Bradley. It is understood that "Chicken Run 2" is the sequel to "Chicken Run" after more than 20 years. The first work was released in China on January 2, 2001. It tells the story of a group of chickens who face the fate of being turned into chicken pies in a chicken factory.

Hayao Miyazaki's animated film 'Porco Rosso' has been extended to January 16 next year, with a Douban score of 8.6 Hayao Miyazaki's animated film 'Porco Rosso' has been extended to January 16 next year, with a Douban score of 8.6 Dec 18, 2023 am 08:07 AM

According to news from this site, Miyazaki Hayao's animated film "Porco Rosso" has announced that it will extend the release date to January 16, 2024. This site previously reported that "Porco Rosso" has been launched in the National Art Federation Special Line Cinema on November 17, with a cumulative box office of over 2,000 10,000, with a Douban score of 8.6, and 85.8% of 4 and 5 star reviews. "Porco Rosso" was produced by Studio Ghibli and directed by Hayao Miyazaki. Moriyama Moriyama, Tokiko Kato, Otsuka Akio, Okamura Akemi and others participated in the dubbing. It was originally released in Japan in 1992. The film is adapted from Hayao Miyazaki's comic book "The Age of Airships" and tells the story of the Italian Air Force's ace pilot Pollock Rosen who was magically turned into a pig. After that, he became a bounty hunter, fighting against air robbers and protecting those around him. Plot synopsis: Rosen is a soldier in World War I

Netflix animated series 'Sonic: Homecoming' Season 3 clips released, to be released next year Netflix animated series 'Sonic: Homecoming' Season 3 clips released, to be released next year Nov 12, 2023 am 09:25 AM

Netflix Sorry, I can help you rewrite the content, but I need to know the original content you want to rewrite. Can you provide it to me? A clip from the third season of the animated series "Sonic: Homecoming Adventures" was announced at Geek Week, which is expected to be launched in 2024. Sorry, I can help you rewrite the content, but I need to know what you want to rewrite. Original content. Can you provide it to me? According to this site, "Sonic: Homecoming Adventure" is produced by Sega and WildBrain. Sorry, I can help you rewrite the content, but I need to know the original content you want to rewrite. Can you provide it to me? Studio Sorry, I can help you rewrite the content, but I need to know the original content you want to rewrite. Can you provide it to me? and sorry i can help you rewrite the content but i need

Best Free AI Animation Art Generator Best Free AI Animation Art Generator Feb 19, 2024 pm 10:50 PM

If you are eager to find the top free AI animation art generator, you can end your search. The world of anime art has been captivating audiences for decades with its unique character designs, captivating colors and captivating plots. However, creating anime art requires talent, skill, and a lot of time. However, with the continuous development of artificial intelligence (AI), you can now explore the world of animation art without having to delve into complex technologies with the help of the best free AI animation art generator. This will open up new possibilities for you to unleash your creativity. What is an AI anime art generator? The AI ​​Animation Art Generator utilizes sophisticated algorithms and machine learning techniques to analyze an extensive database of animation works. Through these algorithms, the system learns and identifies different animation styles

See all articles