LoginSignup
1
0

【React】Webページの背景に動画を流したい!

Posted at

はじめに

Reactで404ページを作ってるとき、サイトの背景が寂しかったので動画を流してみようとふと思いました。

movieフォルダを作成

srcフォルダ内にmovieフォルダを作成。その中に表示したい動画を入れる。

videoタグで読み込む

1番シンプルなのは、videoタグの中にsourceタグを入れてsrcで表示したい動画を指定するとできるみたい。

Page404.tsx
import movie from 'movie/<動画のパス>'

export cosnt Page404 = function page404() {
  <video>
    <source src={movie} type="video/mp4" />
  </video>
}

module not findのエラー

mp4ファイルをインポートすると、module not findのエラーが発生します。
なので、react-app-env.d.tsに設定を追加します。

./src/react-app-env.d.ts
/// <reference types="react-scripts" />  
declare module '*.mp4' {  
  const src: string  
  export default src  
}

Failed to resolve import ~~ Does the file existが起こったら

vite-tsconfig-pathsを使ってtsconfig.jsonにパスエイリアスを設定する。

yarn add --dev vite-tsconfig-paths
/vite.config.ts
import tsconfigPaths from 'vite-tsconfig-paths'

export defaultConfig({
  plugins: [react(), tsconfigPaths()] // 追加
})
tsconfig.json
{
  "baseUrl": "./src" // 追加
}

動画再生の設定

videoタグで再生の設定を書き込んでいきます。

Page404.tsx
<video
  autoPlay // 自動再生 
  loop // 繰り返し再生 
  muted //音声をミュートする
>
</video>

完成コード

Page404.tsx
import { memo } from 'react'  
import background from 'image/YN160326430I9A7076_TP_V.jpg'  
import movie from 'movie/Beach-47073.mp4'  
  
export const Page404 = memo(function page404() {  
  return (  
      <div  
        style={{  
          position: 'fixed',  
          top: 0,  
          right: 0,  
          left: 0,  
          bottom: 0,  
          overflow: 'hidden',  
          height: '100vh',  
          width: '100vw',  
        }}  
      >  
        <video
        . id="video"  
          poster={background}    
          autoPlay  
          loop  
          playsInline  
          muted  
          style={{  
            position: 'absolute',  
            zIndex: -1,  
            objectFit: 'fill',  
            // top:'50%',  
            // left: '50%',
            width: '177.777778vh',  
            height: '56.25vw',  
            minHeight: '100%',  
            minWidth: '100%',  
          }}  
        >  
          <source src={movie} type="video/mp4" />  
        </video>      
        </div> 
    )  
})

movie.gif

参考

ありがとうございました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0