This article mainly introduces the relevant knowledge of canvas to easily and quickly implement the background effect of the Zhihu login page, which has a very good reference value. Let’s take a look at it with the editor
Preface
Open the login page of Zhihu, and you can see that there is an animation in the background, which looks pretty Nice look:
This effect is not difficult to achieve using canvas. Next, we will explain and achieve this effect step by step.
Analysis
Before starting construction, first analyze how the effect works. The first thing to understand is that although it seems that all lines and circles are moving, in fact only circles are moving, and lines are just connecting any two circles that meet certain conditions. Then let’s analyze how the circle moves. From the effect, each circle is moving in a straight line at a uniform speed, and the movement directions are different. From the relevant knowledge of physics, we can know that each circle moves in both the horizontal and vertical directions. There is a speed. Finally, when the circle moves out of any boundary of the canvas, the circle will enter the canvas again from the opposite side of the edge that exits the boundary. It will be much clearer once you understand these three key points.
Practice
Create a canvas first:
// 这里就简单地设置下背景色 <body style="background:#f7fafc;"> <canvas id="canvas" style="width: 100%; height: 100%;"></canvas> </body>
Then get the canvas context and set some common properties
var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); canvas.width = document.documentElement.clientWidth; canvas.height = document.documentElement.clientHeight; context.fillStyle = "rgba(0, 0, 0, 0.08)"; context.strokeStyle = "rgba(0, 0, 0, 0.05)"; context.lineWidth = 0.5;
Next draw a circle, then drawing a circle requires the center coordinates, radius, horizontal speed, and vertical speed of the circle, and this information must meet certain conditions, through a functionTo create:
// 存放所有圆的数组,这里用balls var balls = []; function createBall() { // x坐标 var _x = Math.random() * canvas.width; // y坐标 var _y = Math.random() * canvas.height; // 半径 [0.01, 15.01] var _r = Math.random() * 15 + 0.01; // 水平速度 [±0.0, ±0.5] var _vx = Math.random() * 0.5 * Math.pow( -1, Math.floor(Math.random() * 2 + 1) ); // 垂直速度 [±0.0, ±0.5] var _vy = Math.random() * 0.5 * Math.pow( -1, Math.floor(Math.random() * 2 + 1) ); // 把每一个圆的信息存放到数组中 balls.push({ x: _x, y: _y, r: _r, vx: _vx, vy: _vy }); }
Then choose how many circles you need to draw according to your own situation. Here I assume there are 20, which looks more comfortable:
// 圆的数量 var num = 20; for(var i = 0; i < num; i++) { createBall(); }
Now the circle information is available , the next step is to draw circles and lines in each frame, create an render function, and then draw all the circles within the function:
for(var k = 0; k < num; k++) { context.save(); context.beginPath(); context.arc( balls[k].x, balls[k].y, balls[k].r, 0, Math.PI*2 ); context.fill(); context.restore(); }
Then we need to traverse every two Whether the distance between the centers of the circles is less than a certain critical value (such as 500), if it is satisfied, connect the centers of the two circles:
for(var i = 0; i < num; i++) { for(var j = i + 1; j < num; j++) { if( distance( balls[i], balls[j] ) < 500 ) { context.beginPath(); context.moveTo( balls[i].x, balls[i].y ); context.lineTo( balls[j].x, balls[j].y ); context.stroke(); } } }
The distance function here is to calculate the distance between two points:
function distance(point1, point2) { return Math.sqrt( Math.pow( (point1.x - point2.x), 2 ) + Math.pow( (point1.y - point2.y), 2 ) ); }
The other step is to determine whether the circle exceeds the boundary value. If the conditions are met, then come in again from the opposite side:
for(var k = 0; k < num; k++) { balls[k].x += balls[k].vx; balls[k].y += balls[k].vy; if( balls[k].x - balls[k].r > canvas.width ) { balls[k].x = 0 - balls[k].r; } if( balls[k].x + balls[k].r < 0 ) { balls[k].x = canvas.width + balls[k].r; } if( balls[k].y - balls[k].r > canvas.height ) { balls[k].y = 0 - balls[k].r; } if( balls[k].y + balls[k].r < 0 ) { balls[k].y = canvas.height + balls[k].r; } }
Of course, if you want to make it simple, just remove the circle and restart it as soon as it exceeds the boundary value. Just generate a circle:
if( balls[k].x - balls[k].r > canvas.width || balls[k].x + balls[k].r < 0 || balls[k].y - balls[k].r > canvas.height || balls[k].y + balls[k].r < 0) { balls.splice(k, 1); createBall(); }
In this way, the details of each frame are completed. The last step is to make the circles move:
(function loop(){ render(); requestAnimationFrame(loop); })();
At this point, the entire effect is revealed. Of course, there are many details that you can figure out by yourself to make the effect more delicate and colorful. Hope it helps newbies.
【Related recommendations】
1. Free h5 online video tutorial
3. php.cn original html5 video tutorial
The above is the detailed content of Share the example code of using canvas to implement Zhihu login page. For more information, please follow other related articles on the PHP Chinese website!

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.

SublimeText3 Mac version
God-level code editing software (SublimeText3)