TypeError in React Native using Three.js while trying to make a 3d cube

Viewed 206

I was following this tutorial to make a simple app that shows a 3d cube. This is my code:

import React from 'react'
import {View} from 'react-native'
import Expo from 'expo'
import {Scene, Mesh, MeshBasicMaterial, PerspectiveCamera, BufferGeometry} from 'three'
import ExpoTHREE, {Renderer} from 'expo-three' 
import { ExpoWebGLRenderingContext, GLView } from 'expo-gl'

const App = () => {

const onContextCreate = async (gl) => {
// all THREE.js code
const scene = new Scene()
const camera = new PerspectiveCamera(75,
  gl.drawingBufferWidth/gl.drawingBufferHeight,
  0.1,
  1000)

gl.canvas = {width: gl.drawingBufferWidth, height: gl.drawingBufferHeight}

const renderer = new Renderer({gl})
renderer.setSize(gl.drawingBufferWidth, gl.drawingBufferHeight)

const geometry = new BoxBufferGeometry(1, 1, 1)
const material = new MeshBasicMaterial({color: 'blue'})
const cube = new Mesh(geometry, material)
scene.add(cube)


const render = () => {
    requestAnimationFrame(render)
    renderer.render(scene, camera)
    gl.endFrameEXP()
}

render()
}

return (
<View>
  <GLView style={{flex: 1}}
  onContextCreate = {onContextCreate} />
</View>
)
}

export default App

It seems like at this point the app should show a cube, but I don't see anything and get an error:

Unhandled Rejection (TypeError): Cannot set property canvas of #<"WebGL2RenderingContext"> which has only a getter

This is the line that rises the error:

gl.canvas = {width: gl.drawingBufferWidth, height: gl.drawingBufferHeight}

Could you please help me launch my app properly and get rid of this error? Thanks in advance.

1 Answers

It's hard to tell what the author of the tutorial meant with that line. You could try just delete it since it doesn't work anyway.

You can also follow the official docs, it may be easier to get a working example that way.

GLView docs

expo-three docs

The expo-three docs mention this code, I wonder if it was this that the tutorial was meant to do:

        const { drawingBufferWidth: width, drawingBufferHeight: height } = gl;

        // Create a WebGLRenderer without a DOM element
        const renderer = new Renderer({ gl });
        renderer.setSize(width, height);

example class

Related