Как создать вращающуюся матрицу с помощью React и framer-motion?
Мы можем создать матрицу, используя react с простым CSS и библиотекой framer-motion для их анимации, используя следующий подход:
Предпосылки:
- Знание JavaScript (ES6)
- Знание HTML/CSS.
- Базовые знания ReactJS.
Создание приложения React и установка модуля:
Шаг 1: Создайте приложение React с помощью следующей команды:
npx create-react-app rolling-die
Шаг 2: После создания папки проекта, т. е. Rolling-Die , перейдите к ней с помощью следующей команды:
cd rolling-die
Шаг 3: После создания приложения ReactJS установите модули framer -motion с помощью следующей команды:
$ npm install framer-motion
App.js: Теперь запишите следующий код в файл App.js. Здесь приложение является нашим компонентом по умолчанию, в котором мы написали наш код.
Пример:
App.js
import React, { useState, useEffect } from "react" ; import { motion } from "framer-motion" ; import "./App.css" ; // Animation properties for the container // which is the face of the die const container = { hidden: { opacity: 1, scale: 0 }, visible: { scale: [0, 1], opacity: 1, transition: { staggerChildren: 0.5, delayChildren: 0.5, }, }, }; // Animation properties for the disc(s) that // denote(s) the number player gets after rolling the die const discsOnTheDie = { hidden: { y: 20, opacity: 0 }, visible: { y: 0, opacity: [0.2, 1], }, }; // Utility function to get the random number // from 1 t0 6 just like a physical die const rollTheDie = () => { return Math.floor(Math.random() * 7 + 1); }; const App = () => { // Managing state of randomSize aka number on the die // using useState hook const [randomSize, setRandomSize] = useState(rollTheDie()); const discNumbers = new Array(randomSize); // Assigning 0 to randomSize to the array for ( var i = 0; i < discNumbers.length; i++) { discNumbers[i] = i; } useEffect(() => { // This will fire on every change of randomSize setRandomSize(rollTheDie()); }, [randomSize]); return ( <div> <motion.ul className= "square-container" variants={container} initial= "hidden" animate= "visible" > { /* Mapping javascript array discNumbers */ } {discNumbers.map((index) => ( <motion.li key={index} className= "disc" variants={discsOnTheDie} /> ))} </motion.ul> <button onClick={() => { setRandomSize(); }} > { " " } ROLL{ " " } </button> </div> ); }; export default App; |
App.css
body { overflow : hidden ; width : 100 vw; height : 100 vh; display : flex; justify- content : center ; align-items: center ; background : linear-gradient( 180 deg, green , white ); } .square-container { display : grid; width : 200px ; height : 300px ; border-radius: 50px ; padding : 30px ; gap: 20px ; list-style : none ; grid-template-rows: repeat ( 3 , 1 fr); grid-template-columns: repeat ( 2 , 1 fr); background : rgba( 255 , 255 , 255 , 0.2 ); } . disc { background : white ; border-radius: 100% ; justify- content : center ; align-items: center ; } button { text-decoration : none ; display : inline- block ; margin-left : 80px ; border : none ; color : white ; padding : 15px 32px ; text-align : center ; font-size : 16px ; font-weight : 900 ; border-radius: 50px ; background-color : #4caf50 ; } |
Шаг для запуска приложения: Запустите приложение с помощью следующей команды из корневого каталога проекта.
npm start
Вывод: теперь откройте браузер и перейдите по адресу http://localhost:3000/ , вы увидите следующий вывод: