1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2024-06-06

TL;DR

git clone https://github.com/shinjikuriy/p5js_bun.git

参考URL

始めるにあたって必要なもの

  • Bun
  • お好きなテキストエディタ
  • お好きなWebブラウザ

ここでは Bun v1.2.12 を使っています。最新のものをお使いください。

環境構築手順

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

sh
mkdir p5js_bun && cd p5js_bun
bun init

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

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

sh
bun add p5@1.1.15
bun add -d @types/p5

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

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

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

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

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

Bun.serve のための設定

p5.js を実行し、なおおかつホットリローディングするように Bun server の設定を書きます。

src/index.ts
import { serve } from 'bun'
import homepage from './index.html'

const server = serve({
  routes: {
    '/': homepage,
  },
})

console.log(`Server is running on ${server.url}`)
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>p5js</title>
</head>
<body>
    <script type="module" src="sketch.ts"></script>
</body>
</html>

これで開発環境が整いました。

なお、以上の環境構築手順をまとめたものが、冒頭に記載した Git リポジトリです。
clone してお使いください。

git clone https://github.com/shinjikuriy/p5js_bun.git

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

p5.js のコードは src/sketch.ts に書きます。
インスタンスモードを使いましょう。補完とアノテーションが効きます。

コード例

src/sketch.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);

p5.js のスケッチを実行するために Bun サーバーを立ち上げます。

sh
bun src/index.ts

http://localhost:3000 を見に行くと以下が表示されました。
Screenshot 2025-05-13 at 20.05.11.png

Bun.serve はホットモジュールリローディング機能があるので、コードを変更して保存するとすぐに反映されます。

おわりに

いったん開発環境の構築のみ行いました。
JavaScriptへコンパイルするスクリプトも追って追加したいです。

設定におかしなところや改善できる点があればご教示くださいますと幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?