流場螢幕
Dynamic Flow Fields with Vanilla JS and HTML Canvas
Have you ever been mesmerized by abstract particle animations? These flowing, dynamic visuals can be achieved with surprisingly simple techniques using plain JavaScript and the HTML canvas element. In this article, we will break down the process of creating a flow field that animates thousands of particles, giving them a natural movement.
1. Setting Up the Project
To start, we need three files: an HTML file to set up the canvas, a CSS file for styling, and a JavaScript file for handling the logic.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flow Fields</title> <link rel="stylesheet" href="styles.css"> </head> <body> <canvas id="canvas1"></canvas> <script src="script.js"></script> </body> </html>
Explanation:
- We define a
- The styles.css will be linked to style the canvas.
- The main animation logic is contained in script.js.
2. Styling the Canvas with CSS
Let’s add a simple style to give our canvas a black background and make sure all padding and margins are removed.
* { margin: 0; padding: 0; box-sizing: border-box; } canvas { background-color: black; }
Explanation:
- Setting margin and padding to zero ensures that the canvas fills the entire screen.
- The black background provides a nice contrast for the white particles.
3. Particle Class: Creating the Magic
The Particle class is where the core of the animation lies. Each particle moves across the canvas, leaving a trail of its past locations, creating the flowing effect.
class Particle { constructor(effect) { this.effect = effect; this.x = Math.floor(Math.random() * this.effect.width); this.y = Math.floor(Math.random() * this.effect.height); this.speedModifier = Math.floor(Math.random() * 5 + 1); this.history = [{ x: this.x, y: this.y }]; this.maxLength = Math.floor(Math.random() * 200 + 10); this.timer = this.maxLength * 2; this.colors = ['#4C026B', '#8E0E00', '#9D0208', '#BA1A1A', '#730D9E']; this.color = this.colors[Math.floor(Math.random() * this.colors.length)]; } draw(context) { context.beginPath(); context.moveTo(this.history[0].x, this.history[0].y); for (let i = 1; i < this.history.length; i++) { context.lineTo(this.history[i].x, this.history[i].y); } context.strokeStyle = this.color; context.stroke(); } update() { this.timer--; if (this.timer >= 1) { let x = Math.floor(this.x / this.effect.cellSize); let y = Math.floor(this.y / this.effect.cellSize); let index = y * this.effect.cols + x; let angle = this.effect.flowField[index]; this.speedX = Math.cos(angle); this.speedY = Math.sin(angle); this.x += this.speedX * this.speedModifier; this.y += this.speedY * this.speedModifier; this.history.push({ x: this.x, y: this.y }); if (this.history.length > this.maxLength) { this.history.shift(); } } else if (this.history.length > 1) { this.history.shift(); } else { this.reset(); } } reset() { this.x = Math.floor(Math.random() * this.effect.width); this.y = Math.floor(Math.random() * this.effect.height); this.history = [{ x: this.x, y: this.y }]; this.timer = this.maxLength * 2; } }
Explanation:
- Constructor: Each particle is initialized with a random position and movement speed. The history array tracks past positions to create trails.
- draw(): This function draws the particle’s path based on its history. The particle leaves a colorful trail that adds to the visual effect.
- update(): Here, the particle's position is updated by calculating the angle from the flow field. The speed and direction are controlled by trigonometric functions.
- reset(): When the particle finishes its trail, it is reset to a new random location.
4. Effect Class: Organizing the Animation
The Effect class handles the creation of particles and the flow field itself, which controls the movement of the particles.
class Effect { constructor(canvas) { this.canvas = canvas; this.width = this.canvas.width; this.height = this.canvas.height; this.particles = []; this.numberOfParticles = 3000; this.cellSize = 20; this.flowField = []; this.curve = 5; this.zoom = 0.12; this.debug = true; this.init(); } init() { this.rows = Math.floor(this.height / this.cellSize); this.cols = Math.floor(this.width / this.cellSize); for (let y = 0; y < this.rows; y++) { for (let x = 0; x < this.cols; x++) { let angle = (Math.cos(x * this.zoom) + Math.sin(y * this.zoom)) * this.curve; this.flowField.push(angle); } } for (let i = 0; i < this.numberOfParticles; i++) { this.particles.push(new Particle(this)); } } drawGrid(context) { context.save(); context.strokeStyle = 'white'; context.lineWidth = 0.3; for (let c = 0; c < this.cols; c++) { context.beginPath(); context.moveTo(c * this.cellSize, 0); context.lineTo(c * this.cellSize, this.height); context.stroke(); } for (let r = 0; r < this.rows; r++) { context.beginPath(); context.moveTo(0, r * this.cellSize); context.lineTo(this.width, r * this.cellSize); context.stroke(); } context.restore(); } render(context) { if (this.debug) this.drawGrid(context); this.particles.forEach(particle => { particle.draw(context); particle.update(); }); } }
Explanation:
- Constructor: Initializes the canvas dimensions, the number of particles, and the flow field.
- init(): Calculates the angles for the flow field by combining trigonometric functions for each grid cell. This field influences how particles move.
- drawGrid(): Draws the grid that divides the canvas into cells, used when debugging.
- render(): Calls the draw and update methods for each particle to animate the particles across the canvas.
5. Bringing it to Life with the Animation Loop
To make everything work, we need an animation loop that continuously clears the canvas and re-renders the particles:
const effect = new Effect(canvas); function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); effect.render(ctx); requestAnimationFrame(animate); } animate();
Explanation:
- clearRect(): Clears the canvas on each frame to avoid drawing over previous frames.
- requestAnimationFrame: Keeps the animation smooth by recursively calling the animate() function.
Conclusion
By breaking down the Particle and Effect classes, we have created a fluid and dynamic flow field animation using only vanilla JavaScript. The simplicity of the HTML canvas, combined with JavaScript's trigonometric functions, allows us to build these mesmerizing visual effects.
Feel free to play around with the particle count, colors, or the flow field formula to create your own unique effects!
以上是流場螢幕的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。
