主頁 > 企業開發 > 使用 React Three Fiber 和 GSAP 實作 WebGL 輪播影片

使用 React Three Fiber 和 GSAP 實作 WebGL 輪播影片

2023-05-23 09:12:04 企業開發

參考:Building a WebGL Carousel with React Three Fiber and GSAP

  • 在線 demo
  • github 原始碼

效果來源于由 Eum Ray 創建的網站 alcre.co.kr,具有迷人的視覺效果和互動性,具有可拖動或滾動的輪播,具有有趣的影像展示效果,

本文將使用 WebGL、React Three Fiber 和 GSAP 實作類似的效果,通過本文,可以了解如何使用 WebGL、React Three Fiber 和 GSAP 創建互動式 3D 輪播,

準備

首先,用 createreact app 創建專案

npx create-react-app webgl-carsouel
cd webgl-carsouel
npm start

然后安裝相關依賴

npm i @react-three/fiber @react-three/drei gsap leva react-use -S
  • @react-three/fiber: 用 react 實作的簡化 three.js 寫法的一個非常出名的庫
  • @react-three/drei:@react-three/fiber 生態中的一個非常有用的庫,是對 @react-three/fiber 的增強
  • gsap: 一個非常出名的影片庫
  • leva: @react-three/fiber 生態中用以在幾秒鐘內創建GUI控制元件的庫
  • react-use: 一個流行的 react hooks 庫

1. 生成具有紋理的 3D 平面

首先,創建一個任意大小的平面,放置于原點(0, 0, 0)并面向相機,然后,使用 shaderMaterial 材質將所需影像插入到材質中,修改 UV 位置,讓影像填充整個幾何體表面,

為了實作這一點,需要使用一個 glsl 函式,函式將平面和影像的比例作為轉換引數:

/* 
--------------------------------
Background Cover UV
--------------------------------
u = basic UV
s = plane size
i = image size
*/
vec2 CoverUV(vec2 u, vec2 s, vec2 i) {
  float rs = s.x / s.y; // aspect plane size
  float ri = i.x / i.y; // aspect image size
  vec2 st = rs < ri ? vec2(i.x * s.y / i.y, s.y) : vec2(s.x, i.y * s.x / i.x); // new st
  vec2 o = (rs < ri ? vec2((st.x - s.x) / 2.0, 0.0) : vec2(0.0, (st.y - s.y) / 2.0)) / st; // offset
  return u * s / st + o;
}

接下來,將定義2個 uniformsuResuImageRes,每當改變視口大小時,這2個變數將會隨之改變,使用 uRes 以像素為單位存盤片面的大小,使用 uImageRes 存盤影像紋理的大小,

下面是創建平面和設定著色器材質的代碼:

// Plane.js

import { useEffect, useMemo, useRef } from "react"
import { useThree } from "@react-three/fiber"
import { useTexture } from "@react-three/drei"
import { useControls } from 'leva'

const Plane = () => {
  const $mesh = useRef()
  const { viewport } = useThree()
  const tex = useTexture(
    'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/1.jpg'
  )

  const { width, height } = useControls({
    width: {
      value: 2,
      min: 0.5,
      max: viewport.width,
    },
    height: {
      value: 3,
      min: 0.5,
      max: viewport.height,
    }
  })

  useEffect(() => {
    if ($mesh.current.material) {
      $mesh.current.material.uniforms.uRes.value.x = width
      $mesh.current.material.uniforms.uRes.value.y = height
    }
  }, [viewport, width, height])

  const shaderArgs = useMemo(() => ({
    uniforms: {
      uTex: { value: tex },
      uRes: { value: { x: 1, y: 1 } },
      uImageRes: {
        value: { x: tex.source.data.width, y: tex.source.data.height }
      }
    },
    vertexShader: /* glsl */ `
      varying vec2 vUv;

      void main() {
        vUv = uv;
        vec3 pos = position;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( pos, 1.0 );
      }
    `,
    fragmentShader: /* glsl */ `
      uniform sampler2D uTex;
      uniform vec2 uRes;
      uniform vec2 uImageRes;

      /*
      -------------------------------------
      background Cover UV
      -------------------------------------
      u = basic UV
      s = screen size
      i = image size
      */
      vec2 CoverUV(vec2 u, vec2 s, vec2 i) {
        float rs = s.x / s.y; // aspect screen size
        float ri = i.x / i.y; // aspect image size
        vec2 st = rs < ri ? vec2(i.x * s.y / i.y, s.y) : vec2(s.x, i.y * s.x / i.x); // new st
        vec2 o = (rs < ri ? vec2((st.x - s.x) / 2.0, 0.0) : vec2(0.0, (st.y - s.y) / 2.0)) / st; // offset
        return u * s / st + o;
      }

      varying vec2 vUv;

      void main() {
        vec2 uv = CoverUV(vUv, uRes, uImageRes);
        vec3 tex = texture2D(uTex, uv).rgb;
        gl_FragColor = vec4(tex, 1.0);
      }
    `
  }), [tex])

  return (
    <mesh ref={$mesh}>
      <planeGeometry args={[width, height, 30, 30]} />
      <shaderMaterial args={[shaderArgs]} />
    </mesh>
  )
}

export default Plane

2、向平面添加縮放效果

首先, 設定一個新組件來包裹 <Plane />,用以管理縮放效果的激活和停用,

使用著色器材質 shaderMaterial 調整 mesh 大小可保持幾何空間的尺寸,因此,激活縮放效果后,必須顯示一個新的透明平面,其尺寸與視口相當,方便點擊整個影像恢復到初始狀態,

此外,還需要在平面的著色器中實作波浪效果,

因此,在 uniforms 中添加一個新欄位 uZoomScale,存盤縮放平面的值 xy,從而得到頂點著色器的位置,縮放值通過在平面尺寸和視口尺寸比例來計算:

$mesh.current.material.uniforms.uZoomScale.value.x = viewport.width / width
$mesh.current.material.uniforms.uZoomScale.value.y = viewport.height / height

接下來,在 uniforms 中添加一個新欄位 uProgress,來控制波浪效果的數量,通過使用 GSAP 修改 uProgress,影片實作平滑的緩動效果,

創建波形效果,可以在頂點著色器中使用 sin 函式,函式在平面的 x 和 y 位置上添加波狀運動,

// CarouselItem.js

import { useEffect, useRef, useState } from "react"
import { useThree } from "@react-three/fiber"
import gsap from "gsap"
import Plane from './Plane'

const CarouselItem = () => {
  const $root = useRef()
  const [hover, setHover] = useState(false)
  const [isActive, setIsActive] = useState(false)
  const { viewport } = useThree()

  useEffect(() => {
    gsap.killTweensOf($root.current.position)
    gsap.to($root.current.position, {
      z: isActive ? 0 : -0.01,
      duration: 0.2,
      ease: "power3.out",
      delay: isActive ? 0 : 2
    })
  }, [isActive])

  // hover effect
  useEffect(() => {
    const hoverScale = hover && !isActive ? 1.1 : 1
    gsap.to($root.current.scale, {
      x: hoverScale,
      y: hoverScale,
      duration: 0.5,
      ease: "power3.out"
    })
  }, [hover, isActive])

  const handleClose = (e) => {
    e.stopPropagation()
    if (!isActive) return
    setIsActive(false)
  }

  const textureUrl = 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/1.jpg'


  return (
    <group
      ref={$root}
      onClick={() => setIsActive(true)}
      onPointerEnter={() => setHover(true)}
      onPointerLeave={() => setHover(false)}
    >
      <Plane
        width={1}
        height={2.5}
        texture={textureUrl}
        active={isActive}
      />

      {isActive ? (
        <mesh position={[0, 0, 0]} onClick={handleClose}>
          <planeGeometry args={[viewport.width, viewport.height]} />
          <meshBasicMaterial transparent={true} opacity={0} color="red" />
        </mesh>
      ) : null}
    </group>
  )
}

export default CarouselItem

<Plane /> 組件也要進行更改,支持引數及引數變更處理,更改后:

// Plane.js

import { useEffect, useMemo, useRef } from "react"
import { useThree } from "@react-three/fiber"
import { useTexture } from "@react-three/drei"
import gsap from "gsap"

const Plane = ({ texture, width, height, active, ...props}) => {
  const $mesh = useRef()
  const { viewport } = useThree()
  const tex = useTexture(texture)

  useEffect(() => {
    if ($mesh.current.material) {
      // setting
      $mesh.current.material.uniforms.uZoomScale.value.x = viewport.width / width
      $mesh.current.material.uniforms.uZoomScale.value.y = viewport.height / height

      gsap.to($mesh.current.material.uniforms.uProgress, {
        value: active ? 1 : 0,
        duration: 2.5,
        ease: 'power3.out'
      })

      gsap.to($mesh.current.material.uniforms.uRes.value, {
        x: active ? viewport.width : width,
        y: active? viewport.height : height,
        duration: 2.5,
        ease: 'power3.out'
      })
    }
  }, [viewport, active]);

  const shaderArgs = useMemo(() => ({
    uniforms: {
      uProgress: { value: 0 },
      uZoomScale: { value: { x: 1, y: 1 } },
      uTex: { value: tex },
      uRes: { value: { x: 1, y: 1 } },
      uImageRes: {
        value: { x: tex.source.data.width, y: tex.source.data.height }
      }
    },
    vertexShader: /* glsl */ `
      varying vec2 vUv;
      uniform float uProgress;
      uniform vec2 uZoomScale;

      void main() {
        vUv = uv;
        vec3 pos = position;
        float angle = uProgress * 3.14159265 / 2.;
        float wave = cos(angle);
        float c = sin(length(uv - .5) * 15. + uProgress * 12.) * .5 + .5;
        pos.x *= mix(1., uZoomScale.x + wave * c, uProgress);
        pos.y *= mix(1., uZoomScale.y + wave * c, uProgress);

        gl_Position = projectionMatrix * modelViewMatrix * vec4( pos, 1.0 );
      }
    `,
    fragmentShader: /* glsl */ `
      uniform sampler2D uTex;
      uniform vec2 uRes;
      // uniform vec2 uZoomScale;
      uniform vec2 uImageRes;

      /*
      -------------------------------------
      background Cover UV
      -------------------------------------
      u = basic UV
      s = screen size
      i = image size
      */
      vec2 CoverUV(vec2 u, vec2 s, vec2 i) {
        float rs = s.x / s.y; // aspect screen size
        float ri = i.x / i.y; // aspect image size
        vec2 st = rs < ri ? vec2(i.x * s.y / i.y, s.y) : vec2(s.x, i.y * s.x / i.x); // new st
        vec2 o = (rs < ri ? vec2((st.x - s.x) / 2.0, 0.0) : vec2(0.0, (st.y - s.y) / 2.0)) / st; // offset
        return u * s / st + o;
      }

      varying vec2 vUv;

      void main() {
        vec2 uv = CoverUV(vUv, uRes, uImageRes);
        vec3 tex = texture2D(uTex, uv).rgb;
        gl_FragColor = vec4(tex, 1.0);
      }
    `
  }), [tex])

  return (
    <mesh ref={$mesh} {...props}>
      <planeGeometry args={[width, height, 30, 30]} />
      <shaderMaterial args={[shaderArgs]} />
    </mesh>
  )
}

export default Plane

3、實作可以用滑鼠滾動或拖動移動的影像輪播

這部分是最有趣的,但也是最復雜的,因為必須考慮很多事情,

首先,需要使用 renderSlider 創建一個組用以包含所有影像,影像用 <CarouselItem /> 渲染,
然后,需要使用 renderPlaneEvent() 創建一個片面用以管理事件,

輪播最重要的部分在 useFrame() 中,需要計算滑塊進度,使用 displayItems() 函式設定所有item 位置,

另一個需要考慮的重要方面是 <CarouselItem />z 位置,當它變為活動狀態時,需要使其 z 位置更靠近相機,以便縮放效果不會與其他 meshs 沖突,這也是為什么當退出縮放時,需要 mesh 足夠小以將 z 軸位置恢復為 0 (詳見 <CarouselItem />),也是為什么禁用其他 meshs 的點擊,直到縮放效果被停用,

// data/images.js

const images = [
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/1.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/2.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/3.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/4.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/5.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/6.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/7.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/8.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/9.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/10.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/11.jpg' },
  { image: 'https://raw.githubusercontent.com/supahfunk/webgl-carousel/main/public/img/12.jpg' }
]

export default images
// Carousel.js

import { useEffect, useRef, useState, useMemo } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { usePrevious } from 'react-use'
import gsap from 'gsap'
import CarouselItem from './CarouselItem'
import images from '../data/images'

// Plane settings
const planeSettings = {
  width: 1,
  height: 2.5,
  gap: 0.1
}

// gsap defaults
gsap.defaults({
  duration: 2.5,
  ease: 'power3.out'
})

const Carousel = () => {
  const [$root, setRoot] = useState();

  const [activePlane, setActivePlane] = useState(null);
  const prevActivePlane = usePrevious(activePlane)
  const { viewport } = useThree()

  // vars
  const progress = useRef(0)
  const startX = useRef(0)
  const isDown = useRef(false)
  const speedWheel = 0.02
  const speedDrag = -0.3
  const $items = useMemo(() => {
    if ($root) return $root.children
  }, [$root])

  const displayItems = (item, index, active) => {
    gsap.to(item.position, {
      x: (index - active) * (planeSettings.width + planeSettings.gap),
      y: 0
    })
  }

  useFrame(() => {
    progress.current = Math.max(0, Math.min(progress.current, 100))

    const active = Math.floor((progress.current / 100) * ($items.length - 1))
    $items.forEach((item, index) => displayItems(item, index, active))
  })

  const handleWheel = (e) => {
    if (activePlane !== null) return
    const isVerticalScroll = Math.abs(e.deltaY) > Math.abs(e.deltaX)
    const wheelProgress = isVerticalScroll ? e.deltaY : e.deltaX
    progress.current = progress.current + wheelProgress * speedWheel
  }

  const handleDown = (e) => {
    if (activePlane !== null) return
    isDown.current = true
    startX.current = e.clientX || (e.touches && e.touches[0].clientX) || 0
  }

  const handleUp = () => {
    isDown.current = false
  }

  const handleMove = (e) => {
    if (activePlane !== null || !isDown.current) return
    const x = e.clientX || (e.touches && e.touches[0].clientX) || 0
    const mouseProgress = (x - startX.current) * speedDrag
    progress.current = progress.current + mouseProgress
    startX.current = x
  }

  // click
  useEffect(() => {
    if (!$items) return
    if (activePlane !== null && prevActivePlane === null) {
      progress.current = (activePlane / ($items.length - 1)) * 100
    }
  }, [activePlane, $items]);

  const renderPlaneEvents = () => {
    return (
      <mesh
        position={[0, 0, -0.01]}
        onWheel={handleWheel}
        onPointerDown={handleDown}
        onPointerUp={handleUp}
        onPointerMove={handleMove}
        onPointerLeave={handleUp}
        onPointerCancel={handleUp}
      >
        <planeGeometry args={[viewport.width, viewport.height]} />
        <meshBasicMaterial transparent={true} opacity={0} />
      </mesh>
    )
  }

  const renderSlider = () => {
    return (
      <group ref={setRoot}>
        {images.map((item, i) => (
          <CarouselItem
            width={planeSettings.width}
            height={planeSettings.height}
            setActivePlane={setActivePlane}
            activePlane={activePlane}
            key={item.image}
            item={item}
            index={i}
          />
        ))}
      </group>
    )
  }

  return (
    <group>
      {renderPlaneEvents()}
      {renderSlider()}
    </group>
  )
}

export default Carousel

<CarouselItem> 需要更改,以便根據引數顯示不同的影像,及其他細節處理,更改后如下:

// CarouselItem.js

import { useEffect, useRef, useState } from "react"
import { useThree } from "@react-three/fiber"
import gsap from "gsap"
import Plane from './Plane'

const CarouselItem = ({
  index,
  width,
  height,
  setActivePlane,
  activePlane,
  item
}) => {
  const $root = useRef()
  const [hover, setHover] = useState(false)
  const [isActive, setIsActive] = useState(false)
  const [isCloseActive, setIsCloseActive] = useState(false);
  const { viewport } = useThree()
  const timeoutID = useRef()

  useEffect(() => {
    if (activePlane === index) {
      setIsActive(activePlane === index)
      setIsCloseActive(true)
    } else {
      setIsActive(null)
    }
  }, [activePlane]);
  
  useEffect(() => {
    gsap.killTweensOf($root.current.position)
    gsap.to($root.current.position, {
      z: isActive ? 0 : -0.01,
      duration: 0.2,
      ease: "power3.out",
      delay: isActive ? 0 : 2
    })
  }, [isActive])

  // hover effect
  useEffect(() => {
    const hoverScale = hover && !isActive ? 1.1 : 1
    gsap.to($root.current.scale, {
      x: hoverScale,
      y: hoverScale,
      duration: 0.5,
      ease: "power3.out"
    })
  }, [hover, isActive])

  const handleClose = (e) => {
    e.stopPropagation()
    if (!isActive) return
    setActivePlane(null)
    setHover(false)
    clearTimeout(timeoutID.current)
    timeoutID.current = setTimeout(() => {
      setIsCloseActive(false)
    }, 1500);
    // 這個計時器的持續時間取決于 plane 關閉影片的時間
  }

  return (
    <group
      ref={$root}
      onClick={() => setActivePlane(index)}
      onPointerEnter={() => setHover(true)}
      onPointerLeave={() => setHover(false)}
    >
      <Plane
        width={width}
        height={height}
        texture={item.image}
        active={isActive}
      />

      {isCloseActive ? (
        <mesh position={[0, 0, 0.01]} onClick={handleClose}>
          <planeGeometry args={[viewport.width, viewport.height]} />
          <meshBasicMaterial transparent={true} opacity={0} color="red" />
        </mesh>
      ) : null}
    </group>
  )
}

export default CarouselItem

4、實作后期處理效果,增強輪播體驗

真正吸引我眼球并激發我復制次輪播的是視口邊緣拉伸像素的效果,

過去,我通過 @react-three/postprocessing 來自定義著色器多次實作此效果,然而,最近我一直在使用 MeshTransmissionMaterial,因此有了一個想法,嘗試用這種材料覆寫 mesh 并調整設定實作效果,效果幾乎相同!

訣竅是將 materialthickness 屬性與輪播滾動進度的速度聯系起來,僅此而已,

// PostProcessing.js

import { forwardRef } from "react";
import { useThree } from "@react-three/fiber";
import { MeshTransmissionMaterial } from "@react-three/drei";
import { Color } from "three";
import { useControls } from 'leva'

const PostProcessing = forwardRef((_, ref) => {
  const { viewport } = useThree()

  const { active, ior } = useControls({
    active: { value: true },
    ior: {
      value: 0.9,
      min: 0.8,
      max: 1.2
    }
  })

  return active ? (
    <mesh position={[0, 0, 1]}>
      <planeGeometry args={[viewport.width, viewport.height]} />
      <MeshTransmissionMaterial
        ref={ref}
        background={new Color('white')}
        transmission={0.7}
        roughness={0}
        thickness={0}
        chromaticAberration={0.06}
        anisotropy={0}
        ior={ior}
      />
    </mesh>
  ) : null
})

export default PostProcessing

因為后處理作用于 <Carousel /> 組件,所以需要進行相應的更改,更改后如下:

// Carousel.js

import { useEffect, useRef, useState, useMemo } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { usePrevious } from 'react-use'
import gsap from 'gsap'
import PostProcessing from "./PostProcessing";
import CarouselItem from './CarouselItem'
import { lerp, getPiramidalIndex } from "../utils";
import images from '../data/images'

// Plane settings
const planeSettings = {
  width: 1,
  height: 2.5,
  gap: 0.1
}

// gsap defaults
gsap.defaults({
  duration: 2.5,
  ease: 'power3.out'
})

const Carousel = () => {
  const [$root, setRoot] = useState();
  const $post = useRef()

  const [activePlane, setActivePlane] = useState(null);
  const prevActivePlane = usePrevious(activePlane)
  const { viewport } = useThree()

  // vars
  const progress = useRef(0)
  const startX = useRef(0)
  const isDown = useRef(false)
  const speedWheel = 0.02
  const speedDrag = -0.3
  const oldProgress = useRef(0)
  const speed = useRef(0)
  const $items = useMemo(() => {
    if ($root) return $root.children
  }, [$root])

  const displayItems = (item, index, active) => {
    const piramidalIndex = getPiramidalIndex($items, active)[index]
    gsap.to(item.position, {
      x: (index - active) * (planeSettings.width + planeSettings.gap),
      y: $items.length * -0.1 + piramidalIndex * 0.1
    })
  }

  useFrame(() => {
    progress.current = Math.max(0, Math.min(progress.current, 100))

    const active = Math.floor((progress.current / 100) * ($items.length - 1))
    $items.forEach((item, index) => displayItems(item, index, active))

    speed.current = lerp(speed.current, Math.abs(oldProgress.current - progress.current), 0.1)

    oldProgress.current = lerp(oldProgress.current, progress.current, 0.1)

    if ($post.current) {
      $post.current.thickness = speed.current
    }
  })

  const handleWheel = (e) => {
    if (activePlane !== null) return
    const isVerticalScroll = Math.abs(e.deltaY) > Math.abs(e.deltaX)
    const wheelProgress = isVerticalScroll ? e.deltaY : e.deltaX
    progress.current = progress.current + wheelProgress * speedWheel
  }

  const handleDown = (e) => {
    if (activePlane !== null) return
    isDown.current = true
    startX.current = e.clientX || (e.touches && e.touches[0].clientX) || 0
  }

  const handleUp = () => {
    isDown.current = false
  }

  const handleMove = (e) => {
    if (activePlane !== null || !isDown.current) return
    const x = e.clientX || (e.touches && e.touches[0].clientX) || 0
    const mouseProgress = (x - startX.current) * speedDrag
    progress.current = progress.current + mouseProgress
    startX.current = x
  }

  // click
  useEffect(() => {
    if (!$items) return
    if (activePlane !== null && prevActivePlane === null) {
      progress.current = (activePlane / ($items.length - 1)) * 100
    }
  }, [activePlane, $items]);

  const renderPlaneEvents = () => {
    return (
      <mesh
        position={[0, 0, -0.01]}
        onWheel={handleWheel}
        onPointerDown={handleDown}
        onPointerUp={handleUp}
        onPointerMove={handleMove}
        onPointerLeave={handleUp}
        onPointerCancel={handleUp}
      >
        <planeGeometry args={[viewport.width, viewport.height]} />
        <meshBasicMaterial transparent={true} opacity={0} />
      </mesh>
    )
  }

  const renderSlider = () => {
    return (
      <group ref={setRoot}>
        {images.map((item, i) => (
          <CarouselItem
            width={planeSettings.width}
            height={planeSettings.height}
            setActivePlane={setActivePlane}
            activePlane={activePlane}
            key={item.image}
            item={item}
            index={i}
          />
        ))}
      </group>
    )
  }

  return (
    <group>
      {renderPlaneEvents()}
      {renderSlider()}
      <PostProcessing ref={$post} />
    </group>
  )
}

export default Carousel
// utils/index.js

/**
 * 回傳 v0, v1 之間的一個值,可以根據 t 進行計算
 * 示例:
 * lerp(5, 10, 0) // 5
 * lerp(5, 10, 1) // 10
 * lerp(5, 10, 0.2) // 6
 */
export const lerp = (v0, v1, t) => v0 * (1 - t) + v1 * t

/**
 * 以金字塔形狀回傳索引值遞減的陣列,從具有最大值的指定索引開始,這些索引通常用于在元素之間創建重疊效果
 * 示例:array = [0, 1, 2, 3, 4, 5]
 * getPiramidalIndex(array, 0) // [ 6, 5, 4, 3, 2, 1 ]
 * getPiramidalIndex(array, 1) // [ 5, 6, 5, 4, 3, 2 ]
 * getPiramidalIndex(array, 2) // [ 4, 5, 6, 5, 4, 3 ]
 * getPiramidalIndex(array, 3) // [ 3, 4, 5, 6, 5, 4 ]
 * getPiramidalIndex(array, 4) // [ 2, 3, 4, 5, 6, 5 ]
 * getPiramidalIndex(array, 5) // [ 1, 2, 3, 4, 5, 6 ]
 */
export const getPiramidalIndex = (array, index) => {
  return array.map((_, i) => index === i ? array.length : array.length - Math.abs(index - i))
}

總之,通過使用 React Three Fiber 、GSAP 和一些創造力,可以在 WebGL 中創建令人驚嘆的視覺效果和互動式組件,就像受 alcre.co.kr 啟發的輪播一樣,希望這篇文章對您自己的專案有所幫助和啟發!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/553118.html

標籤:其他

上一篇:記錄--九個超級好用的 Javascript 技巧

下一篇:返回列表

標籤雲
其他(159502) Python(38162) JavaScript(25443) Java(18096) C(15230) 區塊鏈(8267) C#(7972) AI(7469) 爪哇(7425) MySQL(7204) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5871) 数组(5741) R(5409) Linux(5340) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4574) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2433) ASP.NET(2403) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) .NET技术(1975) 功能(1967) Web開發(1951) HtmlCss(1940) C++(1919) python-3.x(1918) 弹簧靴(1913) xml(1889) PostgreSQL(1878) .NETCore(1861) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用 React Three Fiber 和 GSAP 實作 WebGL 輪播影片

    參考:[Building a WebGL Carousel with React Three Fiber and GSAP](https://tympanus.net/codrops/2023/04/27/building-a-webgl-carousel-with-react-three-fibe ......

    uj5u.com 2023-05-23 09:12:04 more
  • 記錄--九個超級好用的 Javascript 技巧

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 前言 在實際的開發作業程序中,積累了一些常見又超級好用的 Javascript 技巧和代碼片段,包括整理的其他大神的 JS 使用技巧,今天篩選了 9 個,以供大家參考。 1、動態加載 JS 檔案 在一些特殊的場景下,特別是一些庫和框架的開 ......

    uj5u.com 2023-05-23 09:11:49 more
  • HTTP1.0、HTTP1.1、HTTP2.0 協議的區別

    HTTP 1.1相比HTTP 1.0具有以下優點: 1. 持久連接 :HTTP 1.1引入了持久連接機制,允許多個請求和回應復用同一個TCP連接。這樣可以減少建立和關閉連接的開銷,提高性能和效率。2. 流水線處理 :HTTP 1.1支持流水線處理,即可以同時發送多個請求,不需要等待前一個請求的回應。 ......

    uj5u.com 2023-05-23 09:11:43 more
  • 學系統集成專案管理工程師(中項)系列24b_資訊系統集成專業技術知識

    ![](https://img2023.cnblogs.com/blog/3076680/202305/3076680-20230510153704868-941917377.png) # 1. 面向物件系統分析與設計 ## 1.1. 基本概念 ### 1.1.1. 物件 #### 1.1.1.1. ......

    uj5u.com 2023-05-23 09:11:00 more
  • 學系統集成專案管理工程師(中項)系列24b_資訊系統集成專業技術知識

    ![](https://img2023.cnblogs.com/blog/3076680/202305/3076680-20230510153704868-941917377.png) # 1. 面向物件系統分析與設計 ## 1.1. 基本概念 ### 1.1.1. 物件 #### 1.1.1.1. ......

    uj5u.com 2023-05-23 09:10:25 more
  • 學系統集成專案管理工程師(中項)系列24a_資訊系統集成專業技術知識

    ![](https://img2023.cnblogs.com/blog/3076680/202305/3076680-20230510152925684-2098118079.png) # 1. 資訊系統的生命周期 ## 1.1. 【19下選10】 ## 1.2. 立項 ### 1.2.1. 形成 ......

    uj5u.com 2023-05-22 07:58:31 more
  • 學系統集成專案管理工程師(中項)系列24a_資訊系統集成專業技術知識

    ![](https://img2023.cnblogs.com/blog/3076680/202305/3076680-20230510152925684-2098118079.png) # 1. 資訊系統的生命周期 ## 1.1. 【19下選10】 ## 1.2. 立項 ### 1.2.1. 形成 ......

    uj5u.com 2023-05-22 07:52:46 more
  • 常見前端安全問題總結

    一、XSS攻擊 全稱跨站腳本攻擊,簡稱XSS攻擊,攻擊者通過在目標網站上HTML注入篡改網頁來插入惡意腳本, 當用戶在瀏覽網頁時獲取用戶的cookie等敏感資訊,進一步做一些其他危害的操作。 根據攻擊的來源,該攻擊還可以分為: 1)存盤型攻擊:一般是在有評論功能的網站將惡意代碼當作評論內容存盤到服務 ......

    uj5u.com 2023-05-21 07:55:03 more
  • 記錄--Vue中如何匯出excel表格

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 一、匯出靜態資料 1、安裝 vue-json-excel npm i vue-json-excel 注意,此插件對node有版本要求,安裝失敗檢查一下報錯是否由于node版本造成! 2、引入并注冊組件(以全域為例) import Vue ......

    uj5u.com 2023-05-21 07:54:49 more
  • Echarts初學(一)

    一、安裝 在需要創建圖表的組件中全域引入 圖表組件中 入門實體圖表 <script setup lang="ts"> //全域引入 import * as echarts from "echarts"; import {onMounted} from "vue"; import TestCharts ......

    uj5u.com 2023-05-21 07:54:35 more