Skip to content

Commit 57893f1

Browse files
committed
オフスクリーンキャンバスのシンプルなサンプルを追加
1 parent 30da87c commit 57893f1

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8" />
5+
<script>
6+
window.addEventListener('load', init);
7+
8+
function init() {
9+
const canvas = document.querySelector('#myCanvas');
10+
const offscreenCanvas = canvas.transferControlToOffscreen();
11+
const worker = new Worker('offscreencanvas_simple_worker.js');
12+
worker.postMessage(
13+
{
14+
type: 'init',
15+
canvas: offscreenCanvas
16+
},
17+
[offscreenCanvas]
18+
);
19+
}
20+
</script>
21+
</head>
22+
<body>
23+
<canvas id="myCanvas"></canvas>
24+
</body>
25+
</html>
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
importScripts("https://cdnjs.cloudflare.com/ajax/libs/three.js/101/three.min.js");
2+
3+
onmessage = event => {
4+
5+
// サイズを指定
6+
const width = 960;
7+
const height = 540;
8+
9+
// メインスレッドからオフスクリーンキャンバスを受け取る
10+
const canvas = event.data.canvas;
11+
canvas.style = { width: 0, height: 0 };
12+
13+
// レンダラーを作成
14+
const renderer = new THREE.WebGLRenderer({ canvas });
15+
renderer.setSize(width, height);
16+
17+
// シーンを作成
18+
const scene = new THREE.Scene();
19+
20+
// カメラを作成
21+
const camera = new THREE.PerspectiveCamera(45, width / height);
22+
23+
// マテリアルを作成する
24+
const material = new THREE.MeshStandardMaterial({ color: 0xffFF00 });
25+
26+
// 平行光源
27+
const directionalLight = new THREE.DirectionalLight(0xffffff);
28+
// シーンに追加
29+
scene.add(directionalLight);
30+
31+
// ビルボードを作成
32+
for (let i = 0; i < 300; i++) {
33+
// 球体を作成
34+
const geometry = new THREE.SphereGeometry(20, 20, 20);
35+
// メッシュを作成
36+
const mesh = new THREE.Mesh(geometry, material);
37+
// 3D空間にメッシュを追加
38+
scene.add(mesh);
39+
mesh.position.set(1000 * (Math.random() - 0.5),
40+
1000 * (Math.random() - 0.5),
41+
1000 * (Math.random() - 0.5));
42+
}
43+
44+
tick();
45+
46+
// 毎フレーム時に実行されるループイベントです
47+
function tick() {
48+
// カメラの自動移動
49+
camera.position.x = 100 * Math.sin(Date.now() / 2000);
50+
camera.position.z = 100 * Math.cos(Date.now() / 2000);
51+
camera.position.y = 50 * Math.sin(Date.now() / 1000) + 60;
52+
camera.lookAt(new THREE.Vector3(0, 0, 0));
53+
54+
// レンダリング
55+
renderer.render(scene, camera);
56+
requestAnimationFrame(tick);
57+
}
58+
};

0 commit comments

Comments
 (0)