JS读取GLB文件二进制

2024-03-05  本文已影响0人  zhuyx0304
a<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input id="myfile" type="file">a
  <script>
    var myfile = document.querySelector("#myfile");

    myfile.addEventListener("change", function(e) {
      const file = e.target.files[0];
      const reader = new FileReader();

      reader.onloadend = function(res) {
        if(res.target.readyState === FileReader.DONE) {
          const arrayBuffer = res.target.result;

          const headerView = new DataView(arrayBuffer, 0, 28);

          const magic = getUint32(headerView, 0);
          const version = getUint32(headerView, 4);
          const length = getUint32(headerView, 8);

          const chunkLength = getUint32(headerView, 12);
          const chunkType = getUint32(headerView, 16);
          const chunkData = getUint32(headerView, 20);

          console.log("magic", magic);
          console.log("version", version);
          console.log("length", length);
          console.log("chunkLength", chunkLength);
          console.log("chunkType", chunkType);
          console.log("chunkData", chunkData);

          const jsonstart = 20;
          const jsonend = jsonstart + chunkLength;

          const jsonDataArrayBuffer = arrayBuffer.slice(jsonstart, jsonend);

          const jsonDataString = new TextDecoder("utf-8").decode(jsonDataArrayBuffer);

          try {
            const jsonobject = JSON.parse(jsonDataString);
            console.log("JSON Content:", jsonobject);
          } catch (error) {
            console.error("Failed to parse JSON: ", error);
          }

        }
      }

      reader.readAsArrayBuffer(file);
    })

    function getUint32(view, byteOffset) {
      return view.getUint32(byteOffset, true);
    }
  </script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读