3Dの球をobnizに表示

このエントリーをはてなブックマークに追加

What's this

部品不要です。
obnizのOLED Displayに3Dを表示します。

Program

<!-- HTML Example -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://unpkg.com/obniz@1.9.1/obniz.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.js"></script>
</head>

<body>
<div id="obniz-debug"></div>
<br>
<div class="text-center">
  <h1> Display Sphere </h1>
</div>

<script>

/* This will be over written on obniz.io webapp page */
var obniz = new Obniz("OBNIZ_ID_HERE");

obniz.onconnect = async function () {
    
  const width = obniz.display.width;
  const height = obniz.display.height;
  
  const ctx = obniz.util.createCanvasContext(width, height);
  
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);

  var renderer = new THREE.WebGLRenderer();
  renderer.setSize(width, height);

  var radius = 60;
  var segments = 10;
  var rings = 5;



  var geometry = new THREE.SphereGeometry(radius, segments, rings);
  var material = new THREE.MeshBasicMaterial({
    color: 0xF3A2B0,
    wireframe: true
  });

  var cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  camera.position.z = 150;
  var duration = 50;
  var time = new Date();

  var render = function() {


    cube.rotation.x += 0.05;
    cube.rotation.y += 0.05;

    renderer.render(scene, camera);
    
    var img2D = new Image();
    img2D.addEventListener("load", function () {
        ctx.clearRect(0, 0, width, height);
        ctx.drawImage(img2D, 0, 0);
        obniz.display.draw(ctx);
    });
    img2D.src = renderer.domElement.toDataURL("img/png");

    requestRender();
  };
  var requestRender = function(){
    let now = new Date();
    if(now - time >=  duration ) {
      time = now;
      requestAnimationFrame(render);
    }else{
      setTimeout(requestRender, now - time - duration);
    }
  };
  requestRender();
}
    
</script>
</body>
</html>

今すぐ実行

HTMLがブラウザで開かれて実行されます。