我希望我的 webgl 应用程序视口和画布能够对浏览器窗口大小更改(包括 F11 按钮)做出反应。 IE。我希望画布始终为 100% 宽度和高度,并且希望视口大小和纵横比合适。前者我通过简单实现:
<canvas style="width: 100%; height:100%;">
虽然我不确定这是否是正确的方法。后者我试图用我在这里找到的一些信息来实现:Webgl gl.viewport更改但显然我做错了一些事情。我确实意识到:
canvas.onresize = resizeViewport;
这是错误的,因为画布的大小不会经常改变(它总是100%的宽度和高度),但我不知道应该怎么做。
这是该应用程序的在线版本:http://nps.netarteria.pl/gallery。
我认为这有效:
var canvas;
var gl;
function render() {
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// Draw a 1 pixel border around the edge using
// the scissor test since it's easier than setting up
// a lot of stuff
gl.clearColor(1, 0, 0, 1); // red
gl.disable(gl.SCISSOR_TEST);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.SCISSOR_TEST);
gl.scissor(1, 1, gl.canvas.width - 2, gl.canvas.height - 2);
gl.clearColor(0, 0, 1, 1); // blue
gl.clear(gl.COLOR_BUFFER_BIT);
};
function resizeCanvas() {
var width = canvas.clientWidth;
var height = canvas.clientHeight;
if (canvas.width != width ||
canvas.height != height) {
canvas.width = width;
canvas.height = height;
// in this case just render when the window is resized.
render();
}
}
function main() {
canvas = document.getElementById("c");
gl = canvas.getContext("webgl");
resizeCanvas();
}
window.addEventListener('resize', resizeCanvas);
main();
html, body {
margin: 0;
height: 100%;
}
#c {
width: 100%;
height: 100%;
display: block;
}
<canvas id="c"></canvas>
据我所知,调整大小仅适用于窗口。遗憾的是,HTML5 规范并未向其他元素添加调整大小事件。 (更新:
ResizeObserver
于2018年添加)
注意:如果您始终在渲染(例如游戏),则无需侦听调整大小事件。只需在渲染循环开始时调用 resizeCanvas 即可。如果浏览器调整了画布大小,无论其容器如何,代码都会看到大小不再匹配并更新画布绘图缓冲区的大小。
渲染画布的正确视口大小几乎总是:
// Set the viewport to be the size of the canvas's drawingBuffer.
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
如果您使用的是典型的 3D 数学库,您还有一个投影矩阵和一个函数(通常称为
perspective
),它采用 fieidOfView、aspect、zNear 和 zFar 参数。几乎所有 WebGL 程序的正确方面是:
// Set the aspect of our perspective matrix to match the size
// the canvas is displayed at.
var aspect = gl.canvas.clientWidth / gl.canvas.clientHeight
???.perspective(fieldOfView, aspect, zNear, zFar);
显然你需要缓存 clientWidth 和 clientHeight。原因是设置
canvas.width
会改变CSS布局,CSS布局可以改变clientHeight
更新了上面的代码。