使用 react-spring 在 React 中建立視差滾動效果.mp4
在這篇文章中,我們將學習如何使用**react-spring**動畫庫在React.js中實現流行的視差效果。視差是沿兩條不同的視線觀察物體時視位置的位移或差異,並透過這兩條視線之間的傾角來測量。視差滾動是一種背景內容移動速度與前景內容不同的效果。那麼,讓我們開始吧。
首先建立一個React專案 -
npx create-react-app tutorialpurpose
進入專案目錄 -
cd tutorialpurpose
示例
安裝以下包 -
npm install react-spring npm i --save @react-spring/parallax
**react-spring**用於向我們的網站新增基於彈簧概念的動畫,此庫將用於新增不同型別的動畫。**react-spring/parallax**將用於新增視差效果。
在**App.js**中新增以下程式碼 -
import React, { useState } from "react";
import { Parallax, ParallaxLayer } from "@reactspring/parallax";
export default function App() {
return (
<Parallax pages={2} style={{ top: "0", left: "0" }}>
<ParallaxLayer
offset={0}
speed={2.5}
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<p>Scroll down</p>
</ParallaxLayer>
<ParallaxLayer
offset={1}
speed={2}
style={{ backgroundColor: "#ff6d6d" }} />
<ParallaxLayer
offset={1}
speed={0.5}
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "white",
}}>
<p>Scroll up
</ParallaxLayer>
</Parallax>
);
}解釋
我們首先建立了一個視差容器。**page**屬性指示視差圖層容器在100%視口中佔據多少空間。
然後我們建立了3個視差圖層元件,其中包含我們的內容。它具有定義運動速度等屬性的屬性。任何位於**parallaxLayer**內部的內容都會將其內部內容應用視差效果。
輸出
執行後,將產生以下輸出 -
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP