Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load OBJ model with three.js in TypeScript

I am using TypeScript and three.d.ts from definitely typed. I have no problems using THREE.JSONLoader, but how do I use an OBJLoader from here in a TypeScript project. I probably need to create an OBJLoader.d.ts file, but I have no idea how to do it and then how to use the created definition. I tried to simply copy the THREE.JSONLoader definition and rename it to OBJLoader, but that didn't work.

like image 801
Eiver Avatar asked May 02 '13 09:05

Eiver


2 Answers

The latest Three.js now has ES Module versions of all the classes in the examples/ folder, along with type declaration files. So, now you can:

import {OBJLoader} from 'three/examples/jsm/loaders/OBJLoader'

And it will be typed in TypeScript as expected (hover on it to see tooltips in VS Code).

like image 147
trusktr Avatar answered Nov 14 '22 01:11

trusktr


This answer was correct at the time of posting, but it's out of date now in 2019. See @trusktr's response below for a better solution today.

Having looked at the source of the OBJLoader here, (and with reference to three.d.ts) a simple objloader.d.ts file might look like this:

/// <reference path="three.d.ts" />

export class OBJLoader extends EventDispatcher {
        constructor();
        load(url: string, callback?: (response:any) => any): void;
        parse(data:any):any; // Not sure if the return value can be typed. Seems to be a group but I can't find a definition for that in three.d.ts?
}

Caveat: this is quickly hacked together and not tested, but may help you to get started.

You would then reference your objloader.d.ts in the same way you are currently using three.d.ts. Don't forget to include both the three.js and OBJLoader.js files in your html page, or import them if you are working with external modules.

like image 26
Jude Fisher Avatar answered Nov 14 '22 01:11

Jude Fisher