Three.js调整画布大小

Abu*_*sae 34 javascript three.js

我一直致力于3D项目,我们使用Three.js Library在Web浏览器中显示3D对象.

问题是:

  • 首先,模型显示在一个小的dom元素中,或者当浏览器窗口本身很小时.
  • 然后,当窗口(或dom元素调整大小)时,模型变为像素化

以下是一些截图:

在调整大小之前:

在此输入图像描述

调整大小后:

在此输入图像描述

调整大小后应该如何:

在此输入图像描述

下面是设置模型尺寸(高度和宽度)的代码部分,如果触发了resize事件,则会调用此函数:

console.log("domChanged fired")

instance.domBoundingBox = instance.dom.getBoundingClientRect();
instance.domCenterPos.x = instance.domBoundingBox.width / 2 + instance.domBoundingBox.left;
instance.domCenterPos.y = instance.domBoundingBox.height / 2 + instance.domBoundingBox.top;

var width = instance.dom.clientWidth, height = instance.dom.clientHeight;
instance.domWidthHalf = width / 2, instance.domHeightHalf = height / 2;

// TODO: fire event to expose it to site developers

// here we should update several values regarding width,height,position
if(instance.cameraReal) {
    instance.cameraReal.aspect = instance.dom.clientWidth / instance.dom.clientHeight;
    instance.cameraReal.updateProjectionMatrix();
}

if(instance.renderer3D)
    instance.renderer3D.setSize(instance.dom.clientWidth, instance.dom.clientHeight);
Run Code Online (Sandbox Code Playgroud)

任何人都可以给我一个提示吗?我已经做了几天,但到目前为止还没有任何线索

Sha*_*ery 84

因此canvas元素可以像其他元素一样调整大小.你想要做的是告诉渲染和相机也调整画布内容的大小.

window.addEventListener( 'resize', onWindowResize, false );

function onWindowResize(){

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}
Run Code Online (Sandbox Code Playgroud)

  • 初学者不会因为使用窗口而绊倒,你可能会使用自己的容器作为渲染器,用窗口替换该容器 (7认同)
  • 只是想将问题的答案与可能存在此问题的其他人分开.很酷的建筑顺便说一句. (5认同)

Abu*_*sae 10

最后问题解决了实际问题来自于因为应用程序正在使用THREE.EffectComposer对象,在类构造函数中创建的composer对象如下所示:

this.composer = new THREE.EffectComposer(this.renderer3D);
Run Code Online (Sandbox Code Playgroud)

因此对于渲染器,作曲家需要在事件处理函数之后更新大小,如下所示:

if(instance.renderer3D)
    instance.renderer3D.setSize(instance.dom.clientWidth, instance.dom.clientHeight);
if(instance.composer)
    instance.composer.setSize(instance.dom.clientWidth, instance.dom.clientHeight);
Run Code Online (Sandbox Code Playgroud)

这完全解决了这个问题:)


agm*_*984 6

我使用React JS将Shawn Whinnery的答案应用于我的需求:

在onMount上启动监听器:

componentDidMount() {
  window.addEventListener('resize', this.handleResize, false)
}
Run Code Online (Sandbox Code Playgroud)

删除onUnmount侦听器(因为我们喜欢垃圾回收):

componentWillUnmount() {
  window.removeEventListener('resize', this.handleResize, false)
}
Run Code Online (Sandbox Code Playgroud)

安装处理程序功能:

handleResize = () => {
  this.camera.aspect = window.innerWidth / window.innerHeight
  this.camera.updateProjectionMatrix()
  this.renderer.setSize(window.innerWidth, window.innerHeight)
}
Run Code Online (Sandbox Code Playgroud)

粗箭头语法用于避免绑定this。如果您具有以下代码,该代码将不起作用:handleResize() { ... }但是,当然,如果将其添加到构造函数中,它将起作用:

this.handleResize = this.handleResize.bind(this)
Run Code Online (Sandbox Code Playgroud)

最后说明:确认您的相机为this.camera,渲染器为this.renderer。除此之外,您应该能够将其全部粘贴。