萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Canvas 2D 流體模擬:貝塞爾曲線繪製水滴與旋轉動畫

核心技術棧

  • CanvasRenderingContext2D:bezierCurveTo、translate、rotate、clearRect
  • Jscex:非同步流程控制(類 async/await 前身)
  • 物理模擬:質點彈簧系統、壓力計算、速度場對流

步驟一:用四條三次貝塞爾曲線繪製橢圓(水滴基礎形狀)

function drawEllipse(ctx, x, y, w, h) {
    var k = 0.5522848; // 魔術常數:4*(sqrt(2)-1)/3 ≈ 0.552
    var ox = (w / 2) * k, oy = (h / 2) * k;
    var xe = x + w, ye = y + h;
    var xm = x + w / 2, ym = y + h / 2;

    ctx.beginPath();
    ctx.moveTo(x, ym);                       // 左中點
    ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);       // 左上弧
    ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);     // 右上弧
    ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);    // 右下弧
    ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);      // 左下弧
    ctx.stroke(); // 或 ctx.fill()
}

步驟二:繞中心旋轉

function drawRotatedEllipse(ctx, cx, cy, w, h, angle) {
    ctx.save();
    ctx.translate(cx, cy);        // 移動原點到中心
    ctx.rotate(angle);            // 旋轉
    drawEllipse(ctx, -w/2, -h/2, w, h); // 以中心為原點繪製
    ctx.restore();
}

步驟三:水滴物理模擬(簡化版)

// 質點類別
function Particle(x, y) {
    this.pos = { x: x, y: y };
    this.vel = { x: 0, y: 0 };
    this.force = { x: 0, y: 0 };
    this.mass = 1;
}

Particle.prototype.applyForce = function(fx, fy) {
    this.force.x += fx; this.force.y += fy;
};

Particle.prototype.update = function(dt) {
    // F=ma -> a=F/m
    this.vel.x += this.force.x / this.mass * dt;
    this.vel.y += this.force.y / this.mass * dt;
    this.pos.x += this.vel.x * dt;
    this.pos.y += this.vel.y * dt;
    this.force.x = this.force.y = 0;
};

// 彈簧連結
function Spring(p1, p2, restLen, stiffness) {
    this.p1 = p1; this.p2 = p2; this.restLen = restLen; this.k = stiffness;
}
Spring.prototype.solve = function() {
    var dx = this.p2.pos.x - this.p1.pos.x;
    var dy = this.p2.pos.y - this.p1.pos.y;
    var dist = Math.sqrt(dx*dx + dy*dy);
    var force = (dist - this.restLen) * this.k;
    var fx = force * dx / dist;
    var fy = force * dy / dist;
    this.p1.applyForce(fx, fy);
    this.p2.applyForce(-fx, -fy);
};

步驟四:渲染迴圈(配合 Jscex 非同步)

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var particles = [], springs = [];

// 初始化:建立圓形質點環 + 中心點
function init() {
    var N = 30, R = 100, cx = canvas.width/2, cy = canvas.height/2;
    for (var i=0; i

效能優化建議

  • 使用 OffscreenCanvas(Web Worker 渲染)避免阻塞主執行緒。
  • 空間分割(Grid/Quadtree)加速鄰近質點查找。
  • GPU 加速:改用 WebGL/GPGPU 進行大規模流體模擬。

參考資源

  • Jos Stam, "Real-Time Fluid Dynamics for Games" (SIGGRAPH 2003)
  • Mike Bostock, "Visualizing Algorithms" (D3 force layout)
  • Jscex 專案:github.com/JeffreyZhao/jscex
copyright © 萬盛學電腦網 all rights reserved