2017-06-14 133 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;"); 
...