46
26

More than 3 years have passed since last update.

ReactでCanvasを使う

Posted at

ReactでCanvas APIを使う場合どういうタイミングで初期化したらいいかとか
どう状態を持ったらいいか慣れないと結構悩みどころなのでざっくりシンプルなサンプルで実装

app.js
import React,{useState,useEffect} from "react"
import ReactDOM from "react-dom"

const App = () => {
    // contextを状態として持つ
    const [context,setContext] = useState(null)
    // 画像読み込み完了トリガー
    const [loaded,setLoaded] = useState(false)
    // コンポーネントの初期化完了後コンポーネント状態にコンテキストを登録
    useEffect(()=>{
        const canvas = document.getElementById("canvas")
        const canvasContext = canvas.getContext("2d")
        setContext(canvasContext)
    },[])
    // 状態にコンテキストが登録されたらそれに対して操作できる
    useEffect(()=>{
        if(context!==null)
        {
            const img = new Image()
            img.src = "img.jpg" // 描画する画像など
            img.onload = () => {
                context.drawImage(img,0,0)
                // 更にこれに続いて何か処理をしたい場合
                setLoaded(true)
            }
        }
    },[context])
    useEffect(()=>{
        if(loaded)
        {
            // それに続く処理
        }
    },[loaded])
    return <canvas width="1280" height="720" id="canvas"></canvas>
}
ReactDOM.render(<App />, document.getElementById('root'))

のようにHooksのトリガーで順番に制御していけばタイミング問題でそれほど悩まずにReactでもCanvasが使えるはず

46
26
1

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
46
26