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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
