4

I have a question. I know that its not possible to parse .obj 3D graphics file using JavaScript and we have to convert it into some other format (preferably JSON). But I want to know why? Why we can't parse .obj file using JavaScript?

I would really appreciate your comments and answers.

Thanks Vik

2
  • The only real obstacle I see is presenting the data in 3D (which may not be something you need), and getting the file to the JavaScript client. But that can easily be done through a webservice etc or with the new HTML 5 JS File API. Commented May 5, 2011 at 22:21
  • You seay "I know its not possible ... but I want to know why?" ... it does not make sense. How can you say something is not possible, when you don't know why? Commented Sep 5, 2015 at 23:00

4 Answers 4

8

Sure you can... why not? It's a text file, just go ahead and parse it.

Here, I'll even get you started:

var objText = getObjFile();
var obj = {};
var vertexMatches = objText.match(/^v( -?\d+(\.\d+)?){3}$/gm);
if (vertexMatches)
{
    obj.vertices = vertexMatches.map(function(vertex)
    {
        var vertices = vertex.split(" ");
        vertices.shift();
        return vertices;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

3

Of course you can. I have even written my own library for parsing 3D formats - K3D.js. It also supports MD2, 3DS and Collada. OBJ was the easiest to code :)

Comments

0

There are now a few Javascript libraries to read Wavefront OBJ files. This one works well, though only reads OBJ files and does not output them https://www.npmjs.com/package/obj-file-parser. You can also do this with three.js: https://threejs.org/docs/#examples/en/loaders/OBJLoader.

Comments

-1

you can definitely do that! for example:

function parseOBJ(obj) {
    const vertices = [];
    const faces = [];
    const lines = text.split('\n');

    for (let line of lines) {
        const parts = line.trim().split(/\s+/);
        if (parts[0] === 'v') {
            vertices.push({
                x: parseFloat(parts[1]),
                y: parseFloat(parts[2]),
                z: parseFloat(parts[3])
            });
        } else if (parts[0] === 'f') {
            faces.push([
                parseInt(parts[1]) - 1,
                parseInt(parts[2]) - 1,
                parseInt(parts[3]) - 1
            ]);
        }
    }
    return { vertices, faces };
}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.