UNPKG

ng-cw-v12

Version:

Angular UI Component Library

865 lines (853 loc) 43.5 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) : typeof define === 'function' && define.amd ? define('ng-cw-v12/electric-border', ['exports', '@angular/core'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global["ng-cw-v12"] = global["ng-cw-v12"] || {}, global["ng-cw-v12"]["electric-border"] = {}), global.ng.core)); })(this, (function (exports, i0) { 'use strict'; function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var i0__namespace = /*#__PURE__*/_interopNamespace(i0); /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.push(_); } else if (_ = accept(result)) { if (kind === "field") initializers.push(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; } ; function __runInitializers(thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; } ; function __propKey(x) { return typeof x === "symbol" ? x : "".concat(x); } ; function __setFunctionName(f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); } ; function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function () { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } var ElectricBorderDirective = /** @class */ (function () { function ElectricBorderDirective(el, renderer, ngZone) { this.el = el; this.renderer = renderer; this.ngZone = ngZone; /** 边框圆角半径 单位px */ this.ncBorderRadius = 24; /** 边框线宽 单位px */ this.ncBorderWidth = 2; /** 电弧宽度 单位px */ this.ncElectricWidth = 1; /** 颜色 */ this.ncColor = '#5227FF'; /** 动画速度倍率 */ this.ncSpeed = 1; /** 扰动强度(振幅) */ this.ncChaos = 0.12; /** 停止动画时间,ms,0表示不停止 */ this.ncStopTime = 0; /** 是否启用动画 */ this._enabled = true; /** 双向绑定输出事件 */ this.ncEnabledChange = new i0.EventEmitter(); // 动画状态 this.animationId = null; this.time = 0; this.lastFrameTime = 0; this.isInitialized = false; } Object.defineProperty(ElectricBorderDirective.prototype, "ncEnabled", { get: function () { return this._enabled; }, set: function (val) { this._enabled = val !== null && val !== undefined && val !== false && val !== 'false'; }, enumerable: false, configurable: true }); ElectricBorderDirective.prototype.ngOnInit = function () { this.setupHost(); this.createDom(); this.injectStyles(); this.isInitialized = true; if (this.ncEnabled) { this.startAnimation(); } }; ElectricBorderDirective.prototype.ngOnChanges = function (changes) { if (!this.isInitialized) return; // ncColor / ncSpeed / ncChaos / ncElectricWidth / ncBorderRadius 在 drawFrame() 中每帧直接读取,变更自动生效,无需处理。 // ncColor 除 canvas strokeStyle 外还驱动三个 glow DOM 元素,需显式更新。 if (changes['ncColor']) { this.applyColorVar(); } // ncBorderRadius 除 canvas路径圆角 外还影响宿主元素 CSS border-radius(glow 层用 inherit 会跟随),需显式更新。 if (changes['ncBorderRadius']) { this.applyBorderRadius(); } // ncBorderWidth 影响 glow 层 border 宽度(需显式更新) if (changes['ncBorderWidth']) { this.applyBorderWidth(); } // ncEnabled 变化时启停动画 if (changes['ncEnabled']) { if (this.ncEnabled) { this.startAnimation(); } else { this.stopAnimation(); } } }; ElectricBorderDirective.prototype.ngOnDestroy = function () { this.stopAnimation(); if (this.resizeObserver) { this.resizeObserver.disconnect(); } if (this.stopTimer) { clearTimeout(this.stopTimer); } }; // ─── 初始化 ───────────────────────────────────────────────────────────────── ElectricBorderDirective.prototype.setupHost = function () { var host = this.el.nativeElement; var pos = getComputedStyle(host).position; if (!pos || pos === 'static') { this.renderer.setStyle(host, 'position', 'relative'); } this.renderer.setStyle(host, 'isolation', 'isolate'); this.renderer.setStyle(host, 'overflow', 'visible'); this.applyColorVar(); this.applyBorderRadius(); }; ElectricBorderDirective.prototype.applyBorderRadius = function () { this.renderer.setStyle(this.el.nativeElement, 'border-radius', this.ncBorderRadius + "px"); }; ElectricBorderDirective.prototype.applyBorderWidth = function () { if (this.glow1El) { this.renderer.setStyle(this.glow1El, 'border-width', this.ncBorderWidth + "px"); } if (this.glow2El) { this.renderer.setStyle(this.glow2El, 'border-width', this.ncBorderWidth + "px"); } }; ElectricBorderDirective.prototype.applyColorVar = function () { this.renderer.setStyle(this.el.nativeElement, '--electric-border-color', this.ncColor); // 同步更新已存在的 glow 层颜色(ngOnChanges 时也能生效) if (this.glow1El) { this.renderer.setStyle(this.glow1El, 'border-color', "oklch(from " + this.ncColor + " l c h / 0.6)"); } if (this.glow2El) { this.renderer.setStyle(this.glow2El, 'border-color', this.ncColor); } if (this.bgGlowEl) { this.renderer.setStyle(this.bgGlowEl, 'background', "linear-gradient(-30deg, " + this.ncColor + ", transparent, " + this.ncColor + ")"); } }; ElectricBorderDirective.prototype.createDom = function () { var host = this.el.nativeElement; // ── canvas 容器 ── this.canvasContainerEl = this.renderer.createElement('div'); this.renderer.addClass(this.canvasContainerEl, 'nc-eb-canvas-container'); this.setStyles(this.canvasContainerEl, { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', 'pointer-events': 'none', 'z-index': '2' }); // ── canvas ── this.canvasEl = this.renderer.createElement('canvas'); this.renderer.addClass(this.canvasEl, 'nc-eb-canvas'); this.renderer.setStyle(this.canvasEl, 'display', 'block'); this.renderer.appendChild(this.canvasContainerEl, this.canvasEl); this.renderer.appendChild(host, this.canvasContainerEl); // ── glow 层容器 ── this.layersEl = this.renderer.createElement('div'); this.renderer.addClass(this.layersEl, 'nc-eb-layers'); this.setStyles(this.layersEl, { position: 'absolute', inset: '0', 'border-radius': 'inherit', 'pointer-events': 'none', 'z-index': '0' }); var glowBase = { position: 'absolute', inset: '0', 'border-radius': 'inherit', 'pointer-events': 'none', 'box-sizing': 'border-box' }; // nc-eb-glow-1 this.glow1El = this.renderer.createElement('div'); this.renderer.addClass(this.glow1El, 'nc-eb-glow-1'); this.setStyles(this.glow1El, Object.assign(Object.assign({}, glowBase), { border: this.ncBorderWidth + "px solid " + this.ncColor, filter: 'blur(1px)' })); // nc-eb-glow-2 this.glow2El = this.renderer.createElement('div'); this.renderer.addClass(this.glow2El, 'nc-eb-glow-2'); this.setStyles(this.glow2El, Object.assign(Object.assign({}, glowBase), { border: this.ncBorderWidth + "px solid " + this.ncColor, filter: 'blur(4px)' })); // nc-eb-background-glow this.bgGlowEl = this.renderer.createElement('div'); this.renderer.addClass(this.bgGlowEl, 'nc-eb-background-glow'); this.setStyles(this.bgGlowEl, Object.assign(Object.assign({}, glowBase), { 'z-index': '-1', transform: 'scale(1.1)', filter: 'blur(32px)', opacity: '0.3', background: "linear-gradient(-30deg, " + this.ncColor + ", transparent, " + this.ncColor + ")" })); this.renderer.appendChild(this.layersEl, this.glow1El); this.renderer.appendChild(this.layersEl, this.glow2El); this.renderer.appendChild(this.layersEl, this.bgGlowEl); this.renderer.appendChild(host, this.layersEl); }; ElectricBorderDirective.prototype.injectStyles = function () { // oklch() CSS 函数需要现代浏览器,此处通过 <style> 注入 eb-glow 透明度变量 this.styleEl = this.renderer.createElement('style'); var css = "\n [ncElectricBorder] {\n --electric-light-color: oklch(from var(--electric-border-color) l c h);\n }\n "; this.renderer.appendChild(this.styleEl, this.renderer.createText(css)); this.renderer.appendChild(document.head, this.styleEl); }; // ─── 动画控制 ──────────────────────────────────────────────────────────────── ElectricBorderDirective.prototype.startAnimation = function () { var _this = this; if (!this.canvasEl) return; // 显示 canvas 容器和 glow 层 this.renderer.setStyle(this.canvasContainerEl, 'display', 'block'); this.renderer.setStyle(this.layersEl, 'display', 'block'); // 重置时间(避免首帧大幅跳变) this.lastFrameTime = 0; this.ngZone.runOutsideAngular(function () { // 启动 ResizeObserver _this.resizeObserver = new ResizeObserver(function () { return _this.updateCanvasSize(); }); _this.resizeObserver.observe(_this.el.nativeElement); _this.updateCanvasSize(); // 启动 rAF 循环 var loop = function (currentTime) { _this.drawFrame(currentTime); _this.animationId = requestAnimationFrame(loop); }; _this.animationId = requestAnimationFrame(loop); }); // 如果设置了停止时间,则在指定时间后停止 if (this.ncStopTime > 0) { this.stopTimer = setTimeout(function () { _this.stopAnimation(); _this.ncEnabled = false; _this.ncEnabledChange.emit(false); }, this.ncStopTime); } }; ElectricBorderDirective.prototype.stopAnimation = function () { if (this.animationId !== null) { cancelAnimationFrame(this.animationId); this.animationId = null; } if (this.resizeObserver) { this.resizeObserver.disconnect(); } if (this.stopTimer) { clearTimeout(this.stopTimer); this.stopTimer = null; } // 隐藏 canvas 容器和 glow 层 if (this.canvasContainerEl) { this.renderer.setStyle(this.canvasContainerEl, 'display', 'none'); } if (this.layersEl) { this.renderer.setStyle(this.layersEl, 'display', 'none'); } }; // ─── Canvas 绘制 ───────────────────────────────────────────────────────────── ElectricBorderDirective.prototype.updateCanvasSize = function () { var container = this.el.nativeElement; var rect = container.getBoundingClientRect(); var borderOffset = 60; var width = rect.width + borderOffset * 2; var height = rect.height + borderOffset * 2; var dpr = Math.min(window.devicePixelRatio || 1, 2); this.canvasEl.width = width * dpr; this.canvasEl.height = height * dpr; this.canvasEl.style.width = width + "px"; this.canvasEl.style.height = height + "px"; }; ElectricBorderDirective.prototype.drawFrame = function (currentTime) { var canvas = this.canvasEl; var ctx = canvas.getContext('2d'); if (!ctx) return; var deltaTime = this.lastFrameTime === 0 ? 0 : (currentTime - this.lastFrameTime) / 1000; this.time += deltaTime * this.ncSpeed; this.lastFrameTime = currentTime; var dpr = Math.min(window.devicePixelRatio || 1, 2); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.scale(dpr, dpr); ctx.strokeStyle = this.ncColor; ctx.lineWidth = this.ncElectricWidth; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; var borderOffset = 60; var displacement = 60; var canvasW = canvas.width / dpr; var canvasH = canvas.height / dpr; var left = borderOffset; var top = borderOffset; var borderWidth = canvasW - 2 * borderOffset; var borderHeight = canvasH - 2 * borderOffset; var maxRadius = Math.min(borderWidth, borderHeight) / 2; var radius = Math.min(this.ncBorderRadius, maxRadius); var approximatePerimeter = 2 * (borderWidth + borderHeight) + 2 * Math.PI * radius; var sampleCount = Math.floor(approximatePerimeter / 2); // 噪声参数 var octaves = 10; var lacunarity = 1.6; var gain = 0.7; var amplitude = this.ncChaos; var frequency = 10; var baseFlatness = 0; ctx.beginPath(); for (var i = 0; i <= sampleCount; i++) { var progress = i / sampleCount; var point = this.getRoundedRectPoint(progress, left, top, borderWidth, borderHeight, radius); var xNoise = this.octavedNoise(progress * 8, octaves, lacunarity, gain, amplitude, frequency, this.time, 0, baseFlatness); var yNoise = this.octavedNoise(progress * 8, octaves, lacunarity, gain, amplitude, frequency, this.time, 1, baseFlatness); var displacedX = point.x + xNoise * displacement; var displacedY = point.y + yNoise * displacement; if (i === 0) { ctx.moveTo(displacedX, displacedY); } else { ctx.lineTo(displacedX, displacedY); } } ctx.closePath(); ctx.stroke(); }; // ─── 几何与噪声工具方法 ─────────────────────────────────────────────────────── ElectricBorderDirective.prototype.random = function (x) { return (Math.sin(x * 12.9898) * 43758.5453) % 1; }; ElectricBorderDirective.prototype.noise2D = function (x, y) { var i = Math.floor(x); var j = Math.floor(y); var fx = x - i; var fy = y - j; var a = this.random(i + j * 57); var b = this.random(i + 1 + j * 57); var c = this.random(i + (j + 1) * 57); var d = this.random(i + 1 + (j + 1) * 57); var ux = fx * fx * (3.0 - 2.0 * fx); var uy = fy * fy * (3.0 - 2.0 * fy); return a * (1 - ux) * (1 - uy) + b * ux * (1 - uy) + c * (1 - ux) * uy + d * ux * uy; }; ElectricBorderDirective.prototype.octavedNoise = function (x, octaves, lacunarity, gain, baseAmplitude, baseFrequency, time, seed, baseFlatness) { var y = 0; var amplitude = baseAmplitude; var frequency = baseFrequency; for (var i = 0; i < octaves; i++) { var octaveAmplitude = amplitude; if (i === 0) octaveAmplitude *= baseFlatness; y += octaveAmplitude * this.noise2D(frequency * x + seed * 100, time * frequency * 0.3); frequency *= lacunarity; amplitude *= gain; } return y; }; ElectricBorderDirective.prototype.getCornerPoint = function (centerX, centerY, radius, startAngle, arcLength, progress) { var angle = startAngle + progress * arcLength; return { x: centerX + radius * Math.cos(angle), y: centerY + radius * Math.sin(angle) }; }; ElectricBorderDirective.prototype.getRoundedRectPoint = function (t, left, top, width, height, radius) { var straightWidth = width - 2 * radius; var straightHeight = height - 2 * radius; var cornerArc = (Math.PI * radius) / 2; var totalPerimeter = 2 * straightWidth + 2 * straightHeight + 4 * cornerArc; var distance = t * totalPerimeter; var accumulated = 0; // Top edge if (distance <= accumulated + straightWidth) { var progress_1 = (distance - accumulated) / straightWidth; return { x: left + radius + progress_1 * straightWidth, y: top }; } accumulated += straightWidth; // Top-right corner if (distance <= accumulated + cornerArc) { var progress_2 = (distance - accumulated) / cornerArc; return this.getCornerPoint(left + width - radius, top + radius, radius, -Math.PI / 2, Math.PI / 2, progress_2); } accumulated += cornerArc; // Right edge if (distance <= accumulated + straightHeight) { var progress_3 = (distance - accumulated) / straightHeight; return { x: left + width, y: top + radius + progress_3 * straightHeight }; } accumulated += straightHeight; // Bottom-right corner if (distance <= accumulated + cornerArc) { var progress_4 = (distance - accumulated) / cornerArc; return this.getCornerPoint(left + width - radius, top + height - radius, radius, 0, Math.PI / 2, progress_4); } accumulated += cornerArc; // Bottom edge if (distance <= accumulated + straightWidth) { var progress_5 = (distance - accumulated) / straightWidth; return { x: left + width - radius - progress_5 * straightWidth, y: top + height }; } accumulated += straightWidth; // Bottom-left corner if (distance <= accumulated + cornerArc) { var progress_6 = (distance - accumulated) / cornerArc; return this.getCornerPoint(left + radius, top + height - radius, radius, Math.PI / 2, Math.PI / 2, progress_6); } accumulated += cornerArc; // Left edge if (distance <= accumulated + straightHeight) { var progress_7 = (distance - accumulated) / straightHeight; return { x: left, y: top + height - radius - progress_7 * straightHeight }; } accumulated += straightHeight; // Top-left corner var progress = (distance - accumulated) / cornerArc; return this.getCornerPoint(left + radius, top + radius, radius, Math.PI, Math.PI / 2, progress); }; // ─── 工具 ──────────────────────────────────────────────────────────────────── ElectricBorderDirective.prototype.setStyles = function (el, styles) { var _this = this; Object.entries(styles).forEach(function (_a) { var _b = __read(_a, 2), prop = _b[0], value = _b[1]; _this.renderer.setStyle(el, prop, value); }); }; return ElectricBorderDirective; }()); ElectricBorderDirective.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0__namespace, type: ElectricBorderDirective, deps: [{ token: i0__namespace.ElementRef }, { token: i0__namespace.Renderer2 }, { token: i0__namespace.NgZone }], target: i0__namespace.ɵɵFactoryTarget.Directive }); ElectricBorderDirective.ɵdir = i0__namespace.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.1.5", type: ElectricBorderDirective, selector: "[ncElectricBorder]", inputs: { ncBorderRadius: "ncBorderRadius", ncBorderWidth: "ncBorderWidth", ncElectricWidth: "ncElectricWidth", ncColor: "ncColor", ncSpeed: "ncSpeed", ncChaos: "ncChaos", ncStopTime: "ncStopTime", ncEnabled: "ncEnabled" }, outputs: { ncEnabledChange: "ncEnabledChange" }, usesOnChanges: true, ngImport: i0__namespace }); i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0__namespace, type: ElectricBorderDirective, decorators: [{ type: i0.Directive, args: [{ selector: '[ncElectricBorder]' }] }], ctorParameters: function () { return [{ type: i0__namespace.ElementRef }, { type: i0__namespace.Renderer2 }, { type: i0__namespace.NgZone }]; }, propDecorators: { ncBorderRadius: [{ type: i0.Input }], ncBorderWidth: [{ type: i0.Input }], ncElectricWidth: [{ type: i0.Input }], ncColor: [{ type: i0.Input }], ncSpeed: [{ type: i0.Input }], ncChaos: [{ type: i0.Input }], ncStopTime: [{ type: i0.Input }], ncEnabled: [{ type: i0.Input }], ncEnabledChange: [{ type: i0.Output }] } }); var NcElectricBorderModule = /** @class */ (function () { function NcElectricBorderModule() { } return NcElectricBorderModule; }()); NcElectricBorderModule.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0__namespace, type: NcElectricBorderModule, deps: [], target: i0__namespace.ɵɵFactoryTarget.NgModule }); NcElectricBorderModule.ɵmod = i0__namespace.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0__namespace, type: NcElectricBorderModule, declarations: [ElectricBorderDirective], exports: [ElectricBorderDirective] }); NcElectricBorderModule.ɵinj = i0__namespace.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0__namespace, type: NcElectricBorderModule, imports: [[]] }); i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0__namespace, type: NcElectricBorderModule, decorators: [{ type: i0.NgModule, args: [{ declarations: [ ElectricBorderDirective ], imports: [], exports: [ ElectricBorderDirective ] }] }] }); /** * Generated bundle index. Do not edit. */ exports.ElectricBorderDirective = ElectricBorderDirective; exports.NcElectricBorderModule = NcElectricBorderModule; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=ng-cw-v12-electric-border.umd.js.map