Skip to content

波浪線 bg

一條條樸實無華的實線,在極簡的脈動中,為網站添上簡約的詩意。

靈感來源

技術關鍵字

名稱描述
Canvas 2D API基礎的 2D 繪圖 API,可以高效繪製比 DOM 更複雜的圖形
Noise比 Math.random 更自然隨機效果,常用於地形、雲朵、材質等
Pointer 事件偵測滑鼠或觸控點移動、點擊、懸停等等事件,取得座標、目標等等資訊
物理模擬模擬真實世界物理現象,如重力、碰撞、速度等物理效果
Simplex Noise改良版 Perlin Noise,計算更快且無方向性偏差,常用於程序化生成
彈簧阻尼系統以勁度與阻尼常數模擬彈簧的震盪與回彈,常用於自然的 UI 動態回饋

使用範例

基本用法

除了自身整體效果,還可以與滑鼠產生互動。

查看範例原始碼
vue
<template>
  <div class="w-full flex flex-col gap-4">
    <bg-wavy-lines
      :effect
      :mouse-interaction="{ type: mouseInteractionType }"
      class="h-full w-full touch-none example-wrap"
    >
      <div class="absolute left-2 top-2 opacity-10">
        <!-- {{ fps }} -->
      </div>
    </bg-wavy-lines>

    <div class="example-ctrl flex gap-6">
      <select-stepper
        v-model="effect"
        :label="t('effectLabel')"
        class="w-full"
        :options
      />

      <select-stepper
        v-model="mouseInteractionType"
        :label="t('mouseInteractionLabel')"
        class="w-full"
        :options="mouseInteractionTypeOptions"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ComponentProps } from 'vue-component-type-helpers'
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import SelectStepper from '../../select-stepper.vue'
import BgWavyLines from '../bg-wavy-lines.vue'

type Props = ComponentProps<typeof BgWavyLines>

const effect = ref<Props['effect']>('none')
const options: NonNullable<Props['effect']>[] = [
  'none',
  'wind',
  'waves',
  'orogeny',
]

type MouseInteractionType = NonNullable<Props['mouseInteraction']>['type']

const mouseInteractionType = ref<MouseInteractionType>('smear')
const mouseInteractionTypeOptions: MouseInteractionType[] = [
  'smear',
  'black-hole',
  'white-hole',
  'ripple',
]

const { t } = useI18n()
</script>

原理

嘗試直接使用 Canvas 2D API 繪製生成式藝術。

原本想嘗試 GLSL,但是除了他本身很天書以外,要實現互動的限制也很多。

最後還是回到 Canvas 2D API。(´・ω・`)

噪聲演算法

線條自身自然變動的效果基於 Simplex Noise 演算法

噪聲演算法主要用於產生隨機數值,且數值間有一定的連續性,不會像一般的隨機數值(例:Math.random)那樣離散。

因此可用來模擬地形、雲層、水波等自然效果。

不過由於自然現象的複雜性,噪聲演算法也有許多變種,比如 Worley Noise、Fractal Noise、Turbulence Noise 等等,相當有趣。◝( •ω• )◟

原始碼

API

Props

type MouseEffect = {
  type: 'smear';
  radius?: number;
  force?: number;
} | {
  type: 'black-hole';
  radius?: number;
  gravity?: number;
} | {
  type: 'white-hole';
  radius?: number;
  force?: number;
} | {
  /** 點擊後會產生水波 */
  type: 'ripple';
  speed?: number;
  maxRadius?: number;
  amplitude?: number;
}

interface Props {
  /** 線條間距 */
  lineGap?: number;

  /** 線條之點間距 */
  pointGap?: number;

  /** 線條顏色 */
  lineColor?: string;

  /** 各種效果。例:風吹、波動等等 */
  effect?: 'none' | 'wind' | 'waves' | 'orogeny';

  /** 滑鼠互動效果 */
  mouseInteraction?: MouseEffect;
}

v0.71.4