DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
HTML5 Canvas 玻璃碎片特效:用 Delaunay 三角分割模擬碎裂
編輯:HTML5詳解     

今天來做一個視覺效果很不錯的小玩具:一張照片以「玻璃碎片」的姿態散落成無數三角小塊,然後每一塊帶著 3D 翻轉與淡出,猶如玻璃被擊碎後四散飛去。

為什麼是三角形

真實的破裂面是不規則的多邊形,而要把任意形狀的不規則分割自動化,最合適的數學工具就是 Delaunay 三角分割。它給你一堆點,回傳一組三角形索引,特色是盡量避免產生又瘦又長的三角形,視覺上最接近自然的碎玻璃。

整個流程分四步:撒點 → 三角分割 → 算每塊的外接矩形 → 用 canvas 裁切出每一塊碎片。

HTML

<img src="city_copy.jpg" id="src_img" class="hidden">
<div id="container" style="-webkit-perspective: 500px;">
  <div>
    <script src="delaunay.JS"></script>
    <script src="TweenMax.min.JS"></script>
  </div>
</div>

Step 1:撒點並三角分割

這裡用網格撒點再加隨機偏移,讓碎片大小不至于差太多,但邊緣又不會整齊得像是棋盤。offset = 0.5 代表允許在網格基礎上偏移半格。

var imageWidth = 768, imageHeight = 485;
var vertices = [], indices, boxes = [];
var image, fragments = [],
    container = document.getElementById('container');

window.onload = function () {
    image = document.getElementById('src_img');
    triangulate();
    makeBoxes();
    makeFragments();
};

function triangulate() {
    var x, y,
        dx = imageWidth / 8,
        dy = imageHeight / 8,
        offset = 0.5;
    for (var i = 0; i <= imageWidth; i += dx) {
        for (var j = 0; j <= imageHeight; j += dy) {
            if (i && (i !== imageWidth))
                x = i + randomRange(-dx * offset, dx * offset);
            else x = i;
            if (j && (j !== imageHeight))
                y = j + randomRange(-dy * offset, dy * offset);
            else y = j;
            vertices.push([x, y]);
        }
    }
    indices = Delaunay.triangulate(vertices);
}

Step 2:算外接矩形

每個三角形都要一塊自己的 canvas,而 canvas 的尺寸不能大於實際需要的範圍,否則會浪費記憶體與繪製時間。所以取三個頂點的最小/最大 X、Y,就是這塊碎片的邊界。

function makeBoxes() {
    var p0, p1, p2, xMin, xMax, yMin, yMax;
    for (var i = 0; i < indices.length; i += 3) {
        p0 = vertices[indices[i + 0]];
        p1 = vertices[indices[i + 1]];
        p2 = vertices[indices[i + 2]];
        xMin = Math.min(p0[0], p1[0], p2[0]);
        xMax = Math.max(p0[0], p1[0], p2[0]);
        yMin = Math.min(p0[1], p1[1], p2[1]);
        yMax = Math.max(p0[1], p1[1], p2[1]);
        boxes.push({ x: xMin, y: yMin, w: xMax - xMin, h: yMax - yMin });
    }
}

Step 3:裁出每一塊碎片

這是 Fragment 建構子的精髓:建立一塊只夠大的 canvas,把座標系平移到碎片位置,用 beginPath 畫出三角形並 clip(),然後 drawImage 整張原圖——超出三角形範圍的像素會被自動裁掉,留下的就是形狀正確的碎片。

Fragment = function (v0, v1, v2, box) {
    this.v0 = v0; this.v1 = v1; this.v2 = v2; this.box = box;
    this.canvas = document.createElement('canvas');
    this.canvas.width  = this.box.w;
    this.canvas.height = this.box.h;
    this.canvas.style.width  = this.box.w + 'px';
    this.canvas.style.height = this.box.h + 'px';
    this.ctx = this.canvas.getContext('2d');

    TweenMax.set(this.canvas, { x: this.box.x, y: this.box.y });

    this.ctx.translate(-this.box.x, -this.box.y);
    this.ctx.beginPath();
    this.ctx.moveTo(this.v0[0], this.v0[1]);
    this.ctx.lineTo(this.v1[0], this.v1[1]);
    this.ctx.lineTo(this.v2[0], this.v2[1]);
    this.ctx.closePath();
    this.ctx.clip();
    this.ctx.drawImage(image, 0, 0);
};

Step 4:排成動畫時間軸

動畫交給 GreenSock 的 TimelineMax。每塊碎片有自己的時間軸,從螢幕上方大約 1000px 處墜入,落地後往 Z 軸深處退去,同時依奇偶決定翻轉方向、淡出,最後這些子時間軸全部 insert 進一個 repeat: -1 的主時間軸,就形成無限循環。

function makeFragments() {
    var p0, p1, p2, box, fragment;
    TweenMax.set(container, { perspective: 500 });
    var tl0 = new TimelineMax({ repeat: -1 });

    for (var i = 0; i < indices.length; i += 3) {
        p0 = vertices[indices[i + 0]];
        p1 = vertices[indices[i + 1]];
        p2 = vertices[indices[i + 2]];
        box = boxes[i / 3];
        fragment = new Fragment(p0, p1, p2, box);

        var rx = randomRange(30, 60) * ((i % 2) ?  1 : -1);
        var ry = randomRange(30, 60) * ((i % 2) ? -1 :  1);

        var tl1 = new TimelineMax();
        TweenMax.set(fragment.canvas, { y: box.y - 1000 });

        tl1.to(fragment.canvas, randomRange(0.9, 1.1),
               { y: box.y, ease: Back.easeOut });
        tl1.to(fragment.canvas, 0.5,
               { z: -100, ease: Cubic.easeIn, delay: 0.4 });
        tl1.to(fragment.canvas, randomRange(1, 1.2),
               { rotationX: rx, rotationY: ry, z: 250,
                 alpha: 0, ease: Cubic.easeOut });

        tl0.insert(tl1);
        fragments.push(fragment);
        container.appendChild(fragment.canvas);
    }
}

function randomRange(min, max) { return min + (max - min) * Math.random(); }

兩個實務提醒

碎片數量與效能成正比。以 768×485、8×8 網格來說碎片約在一百多塊,桌機沒問題;手機上要留意每塊 canvas 都是獨立的合成層,數量過多會吃光記憶體,建議把網格改粗(例如 dx = imageWidth / 5)以降低碎片數。

另外,perspective 要設在容器的樣式上,而不是碎片本身,3D 景深才會正確。範例中同時寫了 HTML 的 -webkit-perspective 與 TweenMax 的設定,實際上留一處即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved