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

[メモ]Vite + Web Worker使用時の留意事項

Last updated at Posted at 2025-04-02

dom event

dom event(resize, mousedown等)は、worker内で使用できないので、メインスレッドで発火させて値をpostする。

workerファイルの読み込み

以下、2パターンある。
Vite | Web Workers

const worker = new Worker(new URL('./worker.js', import.meta.url), {
  type: 'module',
})
import MyWorker from './worker?worker'

const worker = new MyWorker()

vite pluginの適用

worker.pluginsを設定しないと、buildエラーになる。
Vite | worker.plugins

plugins: [glsl(), tsconfigPaths()],

worker: {
  plugins: () => [glsl(), tsconfigPaths()],
},

Three.jsを使う場合の留意点

OffscreenCanvasにstyle属性を与える

Three.jsは内部でcanvas要素のstyle属性にアクセスします。しかし、OffscreenCanvasはDOM要素ではないため、style属性を持ちません。Three.jsで使用する場合はランタイムエラーを避けるため、OffscreenCanvasオブジェクトに明示的にstyleプロパティを付加します。
Three.jsでオフスクリーンキャンバスを使う

;(offscreenCanvas as any).style = { width: 0, height: 0 };

Textureインポート

three.jsのTextureLoaderは、domに依存した処理のためworker内では使用できない。
代わりにBitmapLoaderを使用する。

注意点としては、Bitmapはalpha値を扱えないので、透過画像を扱いたい場合は適宜alpha map(透過情報を白黒で表したmap)を作る必要がある。

  private async loadAssets() {
    const loader = new THREE.ImageBitmapLoader()
    loader.setOptions({ imageOrientation: 'flipY' })
    const bitmap = await loader.loadAsync(import.meta.env.BASE_URL + 'assets/webgl/sample.webp')

    const texture = new THREE.CanvasTexture(
      bitmap,
      THREE.UVMapping,
      THREE.ClampToEdgeWrapping,
      THREE.ClampToEdgeWrapping,
      THREE.LinearFilter,
      THREE.LinearFilter,
      THREE.RGBAFormat,
      THREE.UnsignedByteType,
    )

    return texture
  }

Three.js | ImageBitmapLoader
bitmap options

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