donmccurdy / three-gltf-viewer

Drag-and-drop preview for glTF 2.0 models in WebGL using three.js.
https://gltf-viewer.donmccurdy.com/
MIT License
2.09k stars 534 forks source link

base64 encoded 3d model in the HTML #309

Closed snapo closed 1 year ago

snapo commented 1 year ago

Hi, (NOT A ISSUE/BUG) I use the library a lot (not a javascript developer, therefore excuse my question) , because i develop locally and do not want to disable CORS , i would like to embed the GLTF file directly base64 encoded...

From the index.html (sample) the filename is then provided to the gltfExplorer.js via a function call. That functioncall is then executed from the gltfExplorer.js

var gltfExplorer = function (menuId, files) {

    window.onload = function () {
        var div = document.getElementById(menuId);
        Ps.initialize(div);
    };

    if (files.length === 0) {
        return;
    }

    var file = files[0];

When i use the default and load the html file i get a CORS error. So because of that and as i re-write the files automatically, i would like to add the file base64 embedded in the javascript or HTML file.

From Stackoverflow i got the following: https://stackoverflow.com/questions/35940290/how-to-convert-base64-string-to-javascript-file-object-like-as-from-file-input-f

But no matter (no javascript developer) how i try it i do not get it working to read the file from a variable (base64 encoded) instead of the fileurl link...

 function dataURLtoFile(dataurl, filename) {

        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), 
            n = bstr.length, 
            u8arr = new Uint8Array(n);

        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }

        return new File([u8arr], filename, {type:mime});
    }

    //Usage example:
    var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');
    console.log(file);

If i get any hint on where everywhere i would have to change it it would be realy appreciated.

donmccurdy commented 1 year ago

Hi @snapo! This seems like a question about the three.js library, I think? I don't know what gltfExplorer.js is, if that's important context. For three.js questions I would recommend asking on https://discourse.threejs.org/, or on the Slack, Discord, and Stack Overflow channels for three.js, listed on the three.js website (https://threejs.org/).

I would also just note that THREE.GLTFLoader's .load( url ) method can be given a Data URI, you don't need to convert it to a File object unless you have a .gltf file with references to other external resources in other Data URIs.

snapo commented 1 year ago

thanks , i will try the .load(urlobject) ... this might help.