Sharing examples of how to implement rain animation in Canvas
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:
Draw the first frame of graphics (using API drawing)
Clear the drawing board (apply clearRect() or fillRect())
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); }
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>
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 = 'rgba(0, 0, 0, .1)';//画板背景,注意最后的透明度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 = 'hsl(180, 100%, 50%)';//雨滴颜色 长方形的填充色 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();
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 = 'rgba(0, 0, 0, .1)';//画板背景,注意最后的透明度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 = 'hsla(180, 100%, 50%, '+this.a+')'; 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();
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!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools