2017-06-14 134 views
0

我有以下代码,我试图将看到的3d(使用REGL)渲染到React组件App中。它似乎首先渲染得很好。但我注意到,如果我调整浏览器窗口的大小,组件呈现的div高度会增加。因此,任何窗口调整意味着直接转换成高度增长,直到div高于窗口。我试图了解REGLREACT如何一起工作,所以我不确定将该行为归因于什么。这可能是我的误解。REGL在React组件中渲染

import React, { 
    Component 
} from 'react'; 
import regl from 'regl'; 

class App extends Component { 
    constructor() { 
    super() 
    this.state = { 
     reglTest: "Test REGL", 
    }; 
    } 
    componentDidMount() { 
    const rootDiv = document.getElementById('reglTest'); 
    console.log(rootDiv); 

    var reglObj = regl({ 
     container: rootDiv, 
    }) 

    reglObj.frame(({ 
     tick 
    }) => { 
     reglObj.clear({ 
     color: [(tick % 100 * 0.01), 0, 0, 1], 
     depth: 1, 
     }); 

     reglObj({ 
     frag: ` 
    void main() { 
    gl_FragColor = vec4(1, 0, 0, 1); 
    }`, 
     vert: ` 
    attribute vec2 position; 
    void main() { 
    gl_Position = vec4(position, 0, 1); 
    }`, 
     attributes: { 
      position: [ 
      [(tick % 100 * 0.01), -1], 
      [-1, 0], 
      [1, 1] 
      ] 
     }, 
     count: 3 
     })() 
    }); 

    } 
    render() { 
    return (<div id = "reglTest" > {this.state.reglTest} < /div>); 
    } 
} 

export default App; 

编辑:

我能够追踪bug被纠正了在REGL文件resize功能。

function resize() { 
    var w = window.innerWidth; 
    var h = window.innerHeight; 
    if (element !== document.body) { 
     var bounds = element.getBoundingClientRect(); 
     w = bounds.right - bounds.left; 
     h = bounds.bottom - bounds.top; 
    } 
    canvas.width = pixelRatio * w; 
    canvas.height = pixelRatio * h; 
    extend(canvas.style, { 
     width: w + 'px', 
     height: h + 'px' 
    }); 
    } 

它计算h卷起一些高值(比方说1000+调整一点点浏览器窗口之后),而window.innerHeight保持在发言权320

回答

1

我对同样的问题感到困惑,事实证明,我可以看到你也使用的示例代码是错误的。

问题出在“Test REGL”字符串(来自状态)。当它被放入与画布相同的div时,getBoundingClientRect()调用将返回canvas元素的高度加上文本字符串的高度。

然后将此高度传递到作为结果增长的画布。

由于帆布必须填写其父DIV完全,它设置在画布到显示是很重要的:“块”

解决方案:

  • 含有画布股利,必须只包含帆布。

而且

  • canvas元素必须样式为:display: "block"

所以,你需要做什么: 清除从比canvas元素其他一切div容器。

例如删除此:{this.state.reglTest}从渲染功能,因此它看起来像这样:

render() { 
    return (<div id = "reglTest" > < /div>); 
} 

和componentDidMount功能,REGL后()被调用。

componentDidMount() { 
    var reglObj = regl({ 
    container: rootDiv, 
    }) 

添加此设置将画布设置为显示块。

const canvas = document.querySelector("#reglTest > canvas:first-of-type"); 
canvas.setAttribute("style", "display:block;"); 

,所以它看起来像这样

componentDidMount() { 
... 
    var reglObj = regl({ 
    container: rootDiv, 
    }) 
const canvas = document.querySelector("#reglTest > canvas:first-of-type"); 
canvas.setAttribute("style", "display:block;"); 
...