0
0

Bun で p5.js の開発環境を構築する

Last updated at Posted at 2024-06-06

TL;DR

p5.jsドロネー三角形分割を行う関数を書きました。
出来はともかくせっかくなのでライブラリとして公開してみたいと思ったのですが、リファクタリングするにあたって、どうせなら TypeScript で書き直して、テストやらなんやらも一緒にやってみようと思いました。

なお、JS のテストフレームワークとしては JestMocha などがあるようですが、今回は Bun でテストもやってみるつもりです。Bunでのテストの構築については後日別記事にしたいです(うまくいかなければ Jest を導入するかもしれません)。

参考URL

環境

Bun v1.1.3
このバージョンであることに特に意味はありません。最新版を使ってください。

環境構築手順

プロジェクトディレクトリを作成し、ディレクトリ下で bun init

sh
mkdir new_p5js_project
cd new_p5js_project/
bun init
bun init helps you get started with a minimal project and tries to guess sensible defaults. Press ^C anytime to quit

package name (new_p5js_project): 
entry point (index.ts): 

Done! A package.json file was saved in the current directory.
 + index.ts
 + .gitignore
 + tsconfig.json (for editor auto-complete)
 + README.md

To get started, run:
  bun run index.ts

npm から p5@types/p5js をインストールする

それぞれ、 p5.js 本体と型情報です。

sh
bun add p5 @types/p5 -d
bun add v1.1.3 (2615dc74)

 installed p5@1.9.4
 installed @types/p5@1.7.6

 2 packages installed

プロジェクトディレクトリは、以下のようなファイル構成になっているはずです。

|--.gitignore
|--README.md
|--bun.lockb
|--index.ts
|--node_modules
|--package.json
|--tsconfig.json

src ディレクトリを作成し、開発用のファイルを置く

sh
mkdir src
mv index.ts src/
touch src/index.html

むろん、このファイル構成は任意です。
シンプルなプロジェクトの場合 src フォルダはなくてもいいと思います。

ともあれ、これで開発環境ができました。

コードを書いて動かしてみる

コード例

src/index.ts
import p5 from 'p5';

const sketch = function(p: p5) {
  let diameter: number;
  p.setup = function() {
    p.createCanvas(p.windowWidth, p.windowHeight);
    p.noLoop();
    p.noStroke();
    p.fill(255);
    p.background(0);

    diameter = p.width <= p.height ? p.width : p.height;
    diameter /= 2;
  };

  p.draw = function() {
    // draw a circle in the middle of the canvas
    p.circle(p.width/2, p.height/2, diameter);
  };
};

new p5(sketch);
src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style type="text/css">
    html, body {
      margin: 0;
      padding: 0;
    }
  </style>
  <title>p5.piyo</title>
</head>
<body>
  <script type="module" src="../out/index.js"></script>
</body>
</html>

<script> の属性は適宜書き換えてください。

バンドルしてブラウザで実行

sh
bun build ./src/index.ts --outdir ./out --watch

--watch オプションを付けることで開発コードに変更があるたびに build しなおしてくれます。
これを VSCode の Live Server などと組み合わせるとより快適に開発ができます。

src/index.html を見に行くと以下が表示されました。
Screenshot 2024-06-06 at 20.39.48.jpg

雑感

Bun はセットアップが楽でインストールも実行も速い。すごい。

あとは、参考 URL にもある通り、インスタンスモードにしたことでテキストエディタ上でも p5.js の Lint や関数のサジェストが効くので楽です。

0
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
0
0