Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="ja">
  <head>
    <title>Add Remove Cube</title>
    <!-- CDNからThree.js読み込み -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <!-- フレームレートの描画 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/10/Stats.js"></script>
    <!-- プロパティのインタラクティブ調整バー描画 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.9/dat.gui.min.js"></script>
    <style>
      body {
        /*ページ全体を使用するためmarginを0に設定
            overflowをhiddenに設定*/
        margin: 0;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <!-- フレームレート表示 -->
    <div id="Stats-output"></div>
    <!-- (表示) 出力を保持する -->
    <div id="WebGL-output"></div>

    <!-- Three.jsコードの記述 -->
    <script type="text/javascript">
      var camera; // カメラ定義
      var scene; // シーン定義
      var renderer; // レンダラー定義

      /* すべての読み込みが終わってからThree.js関連の処理を実行 */
      function init() {
        var stats = initStats(); // フレームレートなど表示

        // オブジェクト、カメラ、ライトなどすべての要素を格納するシーン作成
        scene = new THREE.Scene();
        scene.fog = new THREE.FogExp2(0xffffff, 0.005); // 遠くの物が霞んで見える設定
        // カメラ設定
        camera = new THREE.PerspectiveCamera(
          45, // 視野
          window.innerWidth / window.innerHeight, // アスペクト
          0.1, // どの程度のカメラの距離から描画を始めるか
          1000 // どのくらい遠くまで見えるか
        );
        scene.add(camera); // カメラをシーンに追加

        // Cameraに基づいてブラウザ内でどのように見えるか計算
        renderer = new THREE.WebGLRenderer();
        renderer.setClearColor(new THREE.Color(0xeeeeee)); // レンダラー初期値決定
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMap.enabled = true; // オブジェクトシャドウを有効にする

        // 座標軸をシーンに追加
        // var axes = new THREE.AxisHelper(20);
        // scene.add(axes);

        // 平面作成
        var planeGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // width:60, height:40
        var planeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
        var plane = new THREE.Mesh(planeGeometry, planeMaterial);
        plane.receiveShadow = true; // 影を受ける

        // 回転と位置決め
        plane.rotation.x = -0.5 * Math.PI;
        plane.position.x = 0;
        plane.position.y = 0;
        plane.position.z = 0;

        // シーンに平面を追加
        scene.add(plane);

        // シーンの中心にカメラを向ける
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        // 均等光源
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);

        // 光源をシーンに追加
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-20, 30, -5);
        spotLight.castShadow = true; // 影を落とす
        scene.add(spotLight);
        // レンダラーの出力をhtmlの(WebGL-output)に追加
        document
          .getElementById("WebGL-output")
          .appendChild(renderer.domElement);

        // インタラクティブに調整するプロパティ設定
        var controls = new (function () {
          this.rotationSpeed = 0.02; // 回転速度
          this.numberOfObjects = scene.children.length; // 現在のオブジェクト数
          // キューブを1つ削除する関数
          this.removeCube = function () {
            var allChildren = scene.children; // 子要素をすべて取得
            var lastObject = allChildren[allChildren.length - 1]; // 最後に追加したオブジェクト取得
            // planeでなければキューブを削除
            if (lastObject instanceof THREE.Mesh && lastObject != plane) {
              scene.remove(lastObject);
              // 個数の更新
              this.numberOfObjects = scene.children.length;
            }
          };
          // すべての追加したキューブを一括削除する関数
          this.removeAllCube = function () {
            var allChildren = scene.children;
            var iter = allChildren.length;
            for (var i = iter; i >= 0; --i) {
              var lastObject = allChildren[i];
              if (lastObject instanceof THREE.Mesh && lastObject != plane) {
                scene.remove(lastObject);
              }
            }
            this.numberOfObjects = scene.children.length;
          };
          // キューブを追加する関数
          this.addCube = function () {
            var cubeSize = Math.ceil(Math.random() * 3); // キューブサイズ決定
            var cubeGeometry = new THREE.BoxGeometry( // 正方形のジオメトリ作成
              cubeSize,
              cubeSize,
              cubeSize
            );
            var cubeMaterial = new THREE.MeshLambertMaterial({
              color: Math.random() * 0xffffff, // キューブ色決定
            });
            // キューブメッシュ作成
            var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
            cube.castShadow = true; // 影を落とす
            cube.name = "cube-" + scene.children.length; // メッシュ名称

            // ポジション決定
            cube.position.x =
              -30 + Math.round(Math.random() * planeGeometry.parameters.width);
            cube.position.y = Math.round(Math.random() * 5);
            cube.position.z =
              -20 + Math.round(Math.random() * planeGeometry.parameters.height);
            // シーンにキューブを追加
            scene.add(cube);
            // シーン内オブジェクトの個数更新
            this.numberOfObjects = scene.children.length;
          };
          // シーン内のオブジェクトをコンソール出力
          this.outputObjects = function () {
            console.log(scene.children);
          };
        })();
        // コントロールパネル設定
        var gui = new dat.GUI();
        gui.add(controls, "rotationSpeed", 0, 0.5); // 値の範囲0~0.5
        gui.add(controls, "addCube");
        gui.add(controls, "removeCube");
        gui.add(controls, "removeAllCube");
        gui.add(controls, "outputObjects");
        gui.add(controls, "numberOfObjects").listen();

        // シーンを描画
        render();
        // シーンを描画する関数
        function render() {
          stats.update();

          // 立方体を軸周りに回転
          // traverse : sceneに配置されたすべての子要素や孫要素を
          // 引数として受け取る
          scene.traverse(function (obj) {
            if (obj instanceof THREE.Mesh && obj != plane) {
              obj.rotation.x += controls.rotationSpeed;
              obj.rotation.y += controls.rotationSpeed;
              obj.rotation.z += controls.rotationSpeed;
            }
          });
          // レンダリング(再帰)
          requestAnimationFrame(render);
          // 表示
          renderer.render(scene, camera);
        }

        // フレームレート(fps) or 1フレーム描画にかかる時間(ms)表示
        function initStats() {
          var stats = new Stats();

          stats.setMode(0); // 0:fps, 1:ms

          // 位置設定
          stats.domElement.style.position = "absolute";
          stats.domElement.style.left = "0px";
          stats.domElement.style.top = "0px";
          // 出力をhtmlに追加する
          document.getElementById("Stats-output").appendChild(stats.domElement);

          return stats;
        }
      }

      // 表示領域をウィンドウサイズに合わせる
      function onResize() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
      }

      // 表示が終わってからThree.js関連処理(関数init)を実行
      window.addEventListener("load", init());

      // リサイズイベント
      window.addEventListener("resize", onResize, false);
    </script>
  </body>
</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console