繁体   English   中英

如何使用 React 使普通 Three.js Canvas 跨越网页的视图高度和宽度?

[英]How to make a Plain Three.js Canvas span across the view height and width of a webpage using React?

我正在尝试修改此示例中的代码:

如何将 Threejs 连接到 React?

这是代码:

import React, { Component } from 'react'
import * as THREE from 'three'

class Scene extends Component {
constructor(props) {
super(props)

this.start = this.start.bind(this)
this.stop = this.stop.bind(this)
this.animate = this.animate.bind(this)
}

componentDidMount() {
const width = this.mount.clientWidth
const height = this.mount.clientHeight

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(
  75,
  width / height,
  0.1,
  1000
)
const renderer = new THREE.WebGLRenderer({ antialias: true })
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: '#433F81' })
const cube = new THREE.Mesh(geometry, material)

camera.position.z = 4
scene.add(cube)
renderer.setClearColor('#000000')
renderer.setSize(width, height)

this.scene = scene
this.camera = camera
this.renderer = renderer
this.material = material
this.cube = cube

this.mount.appendChild(this.renderer.domElement)
this.start()
}

componentWillUnmount() {
this.stop()
this.mount.removeChild(this.renderer.domElement)
}

start() {
if (!this.frameId) {
  this.frameId = requestAnimationFrame(this.animate)
}
}

stop() {
  cancelAnimationFrame(this.frameId)
}

animate() {
this.cube.rotation.x += 0.01
this.cube.rotation.y += 0.01

this.renderScene()
this.frameId = window.requestAnimationFrame(this.animate)
}

renderScene() {
  this.renderer.render(this.scene, this.camera)
}

render() {
return (
  <div
    style={{ width: '400px', height: '400px' }}
    ref={(mount) => { this.mount = mount }}
  />
)
}
}

export default Scene

我正在尝试使 canvas 跨越页面的视图高度和视图宽度,以便它可以用于背景

到目前为止,我已经尝试使用 npm 模块

npm install react-native-responsive-view-port --save

并进行修改:

  render() {
    return (
      <div
        style={{ width: vh(100), height: vw(100), }}
        ref={(mount) => { this.mount = mount }}
      />
    )
  }

由于反应似乎不接受百分比,但是我现在收到错误:

Module not found: Can't resolve 'react-native-expo-viewport-units' in 'C:\Users\Gabriel\Desktop\grid_site\src\pages'

有没有人有一个解决方案来帮助我使三个 Js canvas 响应地跨越浏览器 window 的宽度和高度?

您应该能够使用相同的单位和测量值,但在style属性中使用原生 CSS 而不是 JavaScript function:

vh(100)变成100vhvw(100)变成100vw

package 可能不可用的原因之一可能是因为它旨在与 React Native 一起使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM