Open1

p5.js & React & TypeScript

みつよしみつよし

ファイル構成

概要

ファイルの分割と読み込み方法
TypeScript→JavaScriptトランスパイルについては述べない

  • index.html
  • layout.tsx
    • 主にReactを用いたDOMを記述
    • index.jsへトランスパイル
  • source.ts
    • p5を使用した描画処理を記述

index.html

  • 最低限の構成
  • DOMは読み込むindex.jsにより構成する
<html>
  <head></head>
  <body>
    <div id="root"></div>
    <script src="index.js"></script>
  </body>
</html>

layout.tsx

  • Reactを用いたDOMを記述
  • source.tsに記述したp5の処理を読み込む
import p5 from "p5"
import React from "react"
import ReactDOM from "react-dom"

// - source.ts内の情報をDOMに反映させる
// - トランスパイルで出力されるjsのファイル数を削減する
// の理由から、source.tsを直接index.htmlで読み込むのではなく一旦layout.tsxにimportしている
import { main } from "./source"

const App = () => {
  return (
    <div>

      // p5で使用するcanvasの親タグを作成しておく
      // ※ なくてもcanvasは生成されるので動作上問題ないが、他の要素を配置する際に場所が指定できていると便利
      <div id="canvas-parent"></div>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("root"))
const sketch = new p5(main)

source.ts

  • p5を使用した描画処理を記述
import p5 from "p5"

export const main = (p: p5) => {
  p.setup = () => {
    const canvas = p.createCanvas(fieldSize.x, fieldSize.y)
    canvas.id("canvas")
    canvas.parent("canvas-parent")
  }

  p.draw = () => {
    p.background(0)
  }
}