本文分享一個以 jQuery 撰寫的圖片「馬賽克消失」特效插件。它把圖片切分成無數小方塊,再透過動畫讓這些方塊以不同方式散去,呈現有趣的視覺效果。以下說明實作過程。
頁面只需一個容器,點擊後觸發效果:
<h1>單擊圖片,產生效果</h1>
<div class="box"></div>
.box { width: 1000px; height: 600px; }
插件透過參數控制動畫效果、執行時間、圖片路徑,以及馬賽克的水平與垂直數量:
; (function ($) {
var defaults = {
ani: 4, // 動畫效果:1.向中間聚攏 2.向左上角聚攏 3.拉扯消失 4.原地縮小
delay: 3000, // 動畫執行時間
url: "0", // 圖片路徑
count: [20, 20] // 水平與垂直馬賽克數量
};
$.fn.gysMaSaiKe = function (opt) {
opt = $.extend({}, defaults, opt);
if (opt.url == "0") { alert("沒有填寫圖片路徑參數"); return; }
var obj = $(this);
if (obj.css("position") == "static") obj.css({ "position": "relative" });
obj.css("overflow", "hidden");
var objWidth = obj.width(), objHeight = obj.height();
// 依數量切割圖片為一個個 span 方塊
(function (count, url, obj) {
var littleBoxWidth = Math.floor(objWidth / count[0]);
var littleBoxHeight = Math.floor(objHeight / count[1]);
var html = "";
var littleBoxLeft = littleBoxWidth * (-1), littleBoxTop = littleBoxHeight * (-1);
for (var i = 0; i < count[1]; i++) {
littleBoxTop += littleBoxHeight;
for (var j = 0; j < count[0]; j++) {
littleBoxLeft += littleBoxWidth;
html += "<span style='display:block;position:absolute;left:" + littleBoxLeft + "px;top:" + littleBoxTop + "px;width:" + littleBoxWidth + "px;height:" + littleBoxHeight + "px;background-image:url(" + url + ");background-position:" + (littleBoxLeft) * (-1) + "px " + (littleBoxTop) * (-1) + "px;'></span>";
}\br /> littleBoxLeft = littleBoxWidth * (-1);
}\br /> obj.html(html);
})(opt.count, opt.url, obj);
// 依 ani 參數決定動畫效果
var animation = function (ani, delay, objs) {
var res = function () {};
if (ani == 1) { res = function () { objs.animate({ top: objHeight / 2, left: objWidth / 2, opacity: 0 }, delay); setTimeout(function () { obj.html(""); }, delay); }; }
else if (ani == 2) { res = function () { objs.animate({ left: 0, top: 0, opacity: 0 }, delay); setTimeout(function () { obj.html(""); }, delay); }; }\br /> else if (ani == 3) { res = function () { objs.filter(":even").animate({ top: -100, left: -100 }, delay); objs.filter(":odd").animate({ top: -100, left: 900 }, delay); setTimeout(function () { obj.html(""); }, delay); }; }\br /> else { res = function () { objs.animate({ height: 0, width: 0 }, delay); setTimeout(function () { obj.html(""); }, delay); }; }\br /> return res;
} (opt.ani, opt.delay, obj.children());
obj.on("click", "span", animation);
}
})(jQuery);
$(function () {
$(".box").gysMaSaiKe({
count: [10, 15], // 水平與垂直馬賽克數量
ani: 4, // 動畫效果
delay: 5000, // 動畫執行時間
url: "1.jpg" // 圖片路徑
});
});
整個插件的巧思在於:用 background-position 讓每個小方塊顯示圖片的對應局部,拼湊出完整畫面;點擊後再用 animate 讓方塊聚攏、拉扯或縮小消失。要留意的是,馬賽克數量不宜過多,否則計算量太大可能造成瀏覽器卡頓。