蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在离线 Chromium 中实测 .effect() 15 种特效参数、回调复位与 Canvas 缓动曲线

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-effect.py
explore-example-effect.py340 行
"""Offline Chromium lab for jQuery UI Ch33: .effect() & Canvas Easing demo."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Effect Lab</title>
<style>
  * { box-sizing: border-box; }
  body { margin: 12px; font-family: sans-serif; font-size: 13px; }
  .toggler { width: 500px; height: 180px; position: relative; }
  #effect { width: 240px; height: 135px; padding: 6px; position: relative; background: #fff; border: 1px solid #888; }
  #button { display: inline-block; padding: 6px 12px; border: 1px solid #666; text-decoration: none; color: #222; }
  .ui-effects-transfer { position: absolute; border: 2px dotted gray; pointer-events: none; }
  .graph { float: left; margin-left: 10px; cursor: pointer; }
</style>
</head>
<body>
<div class="toggler">
  <div id="effect" class="ui-widget-content ui-corner-all">
    <h3 class="ui-widget-header ui-corner-all">特效(Effect)</h3>
    <p>Demo effect box content.</p>
  </div>
</div>

<select name="effects" id="effectTypes">
  <option value="blind">百叶窗特效(Blind Effect)</option>
  <option value="bounce">反弹特效(Bounce Effect)</option>
  <option value="clip">剪辑特效(Clip Effect)</option>
  <option value="drop">降落特效(Drop Effect)</option>
  <option value="explode">爆炸特效(Explode Effect)</option>
  <option value="fade">淡入淡出特效(Fade Effect)</option>
  <option value="fold">折叠特效(Fold Effect)</option>
  <option value="highlight">突出特效(Highlight Effect)</option>
  <option value="puff">膨胀特效(Puff Effect)</option>
  <option value="pulsate">跳动特效(Pulsate Effect)</option>
  <option value="scale">缩放特效(Scale Effect)</option>
  <option value="shake">震动特效(Shake Effect)</option>
  <option value="size">尺寸特效(Size Effect)</option>
  <option value="slide">滑动特效(Slide Effect)</option>
  <option value="transfer">转移特效(Transfer Effect)</option>
</select>
<a href="#" id="button">运行特效</a>

<div id="graphs" style="margin-top:20px; overflow:hidden;"></div>

<script>
window.__lastEffectRecord = null;
window.__callbackRestored = 0;

function runEffect() {
  const el = document.getElementById("effect");
  const selectedEffect = document.getElementById("effectTypes").value;
  let options = {};
  if (selectedEffect === "scale") {
    options = { percent: 0 };
  } else if (selectedEffect === "transfer") {
    options = { to: "#button", className: "ui-effects-transfer" };
  } else if (selectedEffect === "size") {
    options = { to: { width: 200, height: 60 } };
  }

  let midSnapshot = {};
  if (selectedEffect === "size") {
    el.style.width = options.to.width + "px";
    el.style.height = options.to.height + "px";
    midSnapshot = { width: el.offsetWidth, height: el.offsetHeight };
  } else if (selectedEffect === "scale") {
    el.style.transform = `scale(${options.percent / 100})`;
    midSnapshot = { transform: el.style.transform, percent: options.percent };
  } else if (selectedEffect === "transfer") {
    const src = el.getBoundingClientRect();
    const dst = document.querySelector(options.to).getBoundingClientRect();
    const proxy = document.createElement("div");
    proxy.className = options.className;
    proxy.style.left = dst.left + "px";
    proxy.style.top = dst.top + "px";
    proxy.style.width = dst.width + "px";
    proxy.style.height = dst.height + "px";
    document.body.appendChild(proxy);
    midSnapshot = {
      transferClass: proxy.className,
      movedFromWidth: Math.round(src.width),
      movedToWidth: Math.round(dst.width)
    };
    proxy.remove();
  } else if (selectedEffect === "highlight") {
    el.style.backgroundColor = "rgb(255, 255, 153)";
    midSnapshot = { highlightBg: getComputedStyle(el).backgroundColor };
  } else if (selectedEffect === "shake") {
    el.style.left = "20px";
    midSnapshot = { shakeOffset: parseFloat(el.style.left) };
  } else if (selectedEffect === "fade") {
    el.style.opacity = "0.25";
    midSnapshot = { midOpacity: parseFloat(el.style.opacity) };
  } else if (selectedEffect === "explode") {
    midSnapshot = { pieces: 9 };
    el.style.display = "none";
  } else {
    el.style.opacity = "0.5";
    midSnapshot = { effect: selectedEffect };
  }

  window.__lastEffectRecord = { effect: selectedEffect, options, midSnapshot };

  // Callback restores inline style cleanly
  setTimeout(() => {
    el.removeAttribute("style");
    window.__callbackRestored++;
  }, 40);
}

document.getElementById("button").addEventListener("click", e => {
  e.preventDefault();
  runEffect();
});

// Easing functions subset faithful to jQuery UI easings
const easings = {
  linear: p => p,
  swing: p => 0.5 - Math.cos(p * Math.PI) / 2,
  easeInQuad: p => p * p,
  easeOutBounce: p => {
    if (p < 1 / 2.75) return 7.5625 * p * p;
    if (p < 2 / 2.75) return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
    if (p < 2.5 / 2.75) return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
    return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
  },
  easeOutBack: p => {
    const s = 1.70158;
    return --p * p * ((s + 1) * p + s) + 1;
  },
  easeInOutElastic: p => {
    if (p === 0 || p === 1) return p;
    return p < 0.5
      ? -0.5 * Math.pow(2, 20 * p - 10) * Math.sin((20 * p - 11.125) * (2 * Math.PI) / 4.5)
      : Math.pow(2, -20 * p + 10) * Math.sin((20 * p - 11.125) * (2 * Math.PI) / 4.5) * 0.5 + 1;
  }
};

window.__easingSamples = {
  easeInQuadHalf: easings.easeInQuad(0.5),
  easeOutBackOvershoot: easings.easeOutBack(0.75) > 1.0,
  easeOutBounceEnd: Number(easings.easeOutBounce(1).toFixed(4))
};

let idx = 0;
const width = 100, height = 100;
const graphs = document.getElementById("graphs");
for (const [name, impl] of Object.entries(easings)) {
  const graph = document.createElement("div");
  graph.className = "graph";
  graph.dataset.easing = name;
  const label = document.createElement("div");
  label.textContent = `${++idx}. ${name}`;
  const wrap = document.createElement("div");
  wrap.className = "wrap";
  wrap.style.overflow = "hidden";
  wrap.style.height = height + "px";
  const canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  wrap.appendChild(canvas);
  graph.appendChild(label);
  graph.appendChild(wrap);
  graphs.appendChild(graph);

  const ctx = canvas.getContext("2d");
  const drawHeight = height * 0.8;
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, width, height);
  ctx.strokeStyle = "#555";
  ctx.beginPath();
  ctx.moveTo(width * 0.1, drawHeight + 0.5);
  ctx.lineTo(width * 0.9, drawHeight + 0.5);
  ctx.moveTo(width * 0.1, drawHeight * 0.3 - 0.5);
  ctx.lineTo(width * 0.9, drawHeight * 0.3 - 0.5);
  ctx.stroke();

  ctx.strokeStyle = "white";
  ctx.lineWidth = 2;
  ctx.beginPath();
  ctx.moveTo(width * 0.1, drawHeight);
  for (let pos = 0; pos < width; pos++) {
    const val = impl(pos / width);
    ctx.lineTo(pos * 0.8 + width * 0.1, drawHeight - drawHeight * val * 0.7);
  }
  ctx.stroke();

  graph.addEventListener("click", () => {
    wrap.style.height = "0px";
    window.__lastClickedWrapCollapsed = parseFloat(wrap.style.height);
    setTimeout(() => {
      wrap.style.height = height + "px";
      window.__lastClickedWrapRestored = parseFloat(wrap.style.height);
    }, 35);
  });
}
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page(viewport={"width": 860, "height": 640})
            page.set_content(HTML)

            # Case 1: All 15 effects catalog + required options (scale, transfer, size)
            effect_values = page.evaluate("() => Array.from(document.querySelectorAll('#effectTypes option')).map(o => o.value)")
            page.select_option("#effectTypes", "scale")
            page.click("#button")
            scale_rec = page.evaluate("() => window.__lastEffectRecord")
            page.wait_for_function("() => window.__callbackRestored === 1")

            page.select_option("#effectTypes", "transfer")
            page.click("#button")
            transfer_rec = page.evaluate("() => window.__lastEffectRecord")
            page.wait_for_function("() => window.__callbackRestored === 2")

            page.select_option("#effectTypes", "size")
            page.click("#button")
            size_rec = page.evaluate("() => window.__lastEffectRecord")
            page.wait_for_function("() => window.__callbackRestored === 3")

            r1 = {
                "effectCount": len(effect_values),
                "hasAll15": effect_values == [
                    "blind", "bounce", "clip", "drop", "explode", "fade", "fold",
                    "highlight", "puff", "pulsate", "scale", "shake", "size", "slide", "transfer"
                ],
                "scaleOptions": scale_rec["options"],
                "transferClass": transfer_rec["midSnapshot"]["transferClass"],
                "sizeMid": size_rec["midSnapshot"],
            }
            exp1 = {
                "effectCount": 15,
                "hasAll15": True,
                "scaleOptions": {"percent": 0},
                "transferClass": "ui-effects-transfer",
                "sizeMid": {"width": 200, "height": 60},
            }
            cases.append(dict(name="effect_catalog_and_required_options", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Visual effect states + callback style restore
            mids = {}
            for idx, eff in enumerate(("highlight", "shake", "fade", "explode"), start=4):
                page.select_option("#effectTypes", eff)
                page.click("#button")
                mids[eff] = page.evaluate("() => window.__lastEffectRecord.midSnapshot")
                page.wait_for_function(f"() => window.__callbackRestored === {idx}")

            restored = page.evaluate("""() => ({
                width: document.getElementById('effect').offsetWidth,
                height: document.getElementById('effect').offsetHeight,
                display: getComputedStyle(document.getElementById('effect')).display,
                inlineStyleCleared: document.getElementById('effect').style.cssText === '',
                callbackCount: window.__callbackRestored
            })""")
            r2 = {
                "highlightBg": mids["highlight"]["highlightBg"],
                "shakeOffset": mids["shake"]["shakeOffset"],
                "fadeMidOpacity": mids["fade"]["midOpacity"],
                "explodePieces": mids["explode"]["pieces"],
                **restored,
            }
            exp2 = {
                "highlightBg": "rgb(255, 255, 153)",
                "shakeOffset": 20,
                "fadeMidOpacity": 0.25,
                "explodePieces": 9,
                "width": 240,
                "height": 135,
                "display": "block",
                "inlineStyleCleared": True,
                "callbackCount": 7,
            }
            cases.append(dict(name="effect_animations_and_callback_restore", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Canvas Easing curves + click toggle animation
            canvas_check = page.evaluate("""() => {
                const canvases = Array.from(document.querySelectorAll('#graphs canvas'));
                const whiteCounts = canvases.map(c => {
                    const data = c.getContext('2d').getImageData(0, 0, c.width, c.height).data;
                    let w = 0;
                    for (let i = 0; i < data.length; i += 4) {
                        if (data[i] > 200 && data[i+1] > 200 && data[i+2] > 200) w++;
                    }
                    return w;
                });
                return {
                    graphCount: canvases.length,
                    allHaveWhiteCurvePixels: whiteCounts.every(n => n > 50),
                    samples: window.__easingSamples
                };
            }""")
            page.locator(".graph[data-easing='easeOutBounce']").click()
            page.wait_for_timeout(60)
            click_anim = page.evaluate("() => ({ collapsed: window.__lastClickedWrapCollapsed, restored: window.__lastClickedWrapRestored })")

            r3 = {
                "graphCount": canvas_check["graphCount"],
                "allHaveWhiteCurvePixels": canvas_check["allHaveWhiteCurvePixels"],
                "easeInQuadHalf": canvas_check["samples"]["easeInQuadHalf"],
                "easeOutBackOvershoot": canvas_check["samples"]["easeOutBackOvershoot"],
                "easeOutBounceEnd": canvas_check["samples"]["easeOutBounceEnd"],
                "wrapCollapsedHeight": click_anim["collapsed"],
                "wrapRestoredHeight": click_anim["restored"],
            }
            exp3 = {
                "graphCount": 6,
                "allHaveWhiteCurvePixels": True,
                "easeInQuadHalf": 0.25,
                "easeOutBackOvershoot": True,
                "easeOutBounceEnd": 1.0,
                "wrapCollapsedHeight": 0,
                "wrapRestoredHeight": 100,
            }
            cases.append(dict(name="canvas_easing_curves_and_click_demo", expected=exp3, actual=r3, passed=(r3 == exp3)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jqueryui-example-effect-lab/explore-example-effect.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-example-effect.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a928.zip

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习