Skip to content

Instantly share code, notes, and snippets.

@andrewimm
Created November 30, 2017 21:53
Show Gist options
  • Save andrewimm/a7c4e73e5220558281fd0df976fab55e to your computer and use it in GitHub Desktop.
Save andrewimm/a7c4e73e5220558281fd0df976fab55e to your computer and use it in GitHub Desktop.
Google Poly API + React VR
import React from 'react';
import {Model} from 'react-vr';
function getFormat(formats, format) {
for (let i = 0; i < formats.length; i++) {
if (formats[i].formatType === format) {
return formats[i];
}
}
}
export default function(key) {
return class PolyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
obj: null,
mtl: null,
};
this._fetchResource(props.assetID);
}
_fetchResource(assetID) {
if (!assetID) {
this.setState({
obj: null,
mtl: null,
});
}
const url = `https://poly.googleapis.com/v1/assets/${assetID}/?key=${key}`;
fetch(url).then((response) => {
if (this.props.assetID !== assetID) {
// If the prop has changed since we started the request, don't go any further
return;
}
response.json().then((json) => {
const format = getFormat(json.formats, 'OBJ');
if (format) {
this.setState({
obj: format.root.url,
mtl: format.resources[0].url,
});
} else {
this.setState({
obj: null,
mtl: null,
});
}
});
});
}
componentWillReceiveProps(nextProps) {
this._fetchResource(nextProps.assetID);
}
render() {
if (!this.state.obj || !this.state.mtl) {
return null;
}
return (
<Model
source={{
obj: {uri: this.state.obj},
mtl: {uri: this.state.mtl},
}}
{...this.props}
/>
);
}
}
}
import React from 'react';
import {AppRegistry, AmbientLight, PointLight, View} from 'react-vr';
import createPolyComponent from './createPolyComponent';
// Create a component bound to your Google Poly API Key
const PolyComponent = createPolyComponent('API_KEY_HERE');
class PolyDemo extends React.Component {
render() {
return (
<View>
<PolyComponent
assetID={'5vbJ5vildOq'}
lit={true}
style={{transform: [{translate: [0, -2, -4]}, {rotateY: '-30deg'}]}}
/>
<PointLight style={{transform: [{translate: [0, 1, 2]}]}} />
<AmbientLight intensity={0.3} />
</View>
);
}
}
AppRegistry.registerComponent('PolyDemo', () => PolyDemo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment