stencil test(蒙板) demo的显示效果

这个例子由四个源文件构成
webgl.html
<html>
<head>
<!--
Title: JavaScript-WebGL2学习笔记四-Stencil
Date: 2018-3-22
Author: kagula
Prologue:
为了让自己在WebGl中如何使用stencil test有个概念,画出三个Shape做测试!
Description:
第一个红色正方形用来设置stencil buffer.
第二个绿色四边形用来演示,只显示同stencil buffer相交的区域.
第三个蓝色矩形用来演示,只显示同stencil buffer不相交的区域.
Reference:
[1]https://www.cnblogs.com/aokman/archive/2010/12/13/1904723.html
[2]https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/stencilFunc
Run environment
[1]Chrome 65.0.3325.162
[2]nginx 1.12.2
Remark
[1]顺便测试了在一次drawScene中使用两个shader程序。
-->
<title>JavaScript-WebGL2学习笔记四-Stencil蒙板</title>
<meta charset="utf-8">
<!-- gl-matrix version 2.4.0 from http://glmatrix.net/ -->
<script type="text/javascript" src="/gl-matrix-min.js"></script>
<script type="text/javascript" src="webgl_helper.js"></script>
<script type="text/javascript" src="shader.js"></script>
<script type="text/javascript" src="shape.js"></script>
</head>
<body>
<canvas id="glCanvas" width="320" height="200"></canvas>
</body>
</html>
<script>
main();
function main() {
//选择器的使用
//http://www.runoob.com/jsref/met-document-queryselector.html
const canvas = document.querySelector("#glCanvas");
// Initialize the GL context
//设置stencil=true, 在webgl上下文中启用stencil buffer.
const gl = canvas.getContext("webgl2", {stencil: true});
// Only continue if WebGL is available and working
if (!gl) {
alert("Unable to initialize WebGL. Your browser or machine may not support it.");
return;
}
var contextAttributes = gl.getContextAttributes();
var haveStencilBuffer = contextAttributes.stencil;
if (!haveStencilBuffer) {
alert("Unable to support stencil.");
return;
}
initShader(gl);
//initBuffers(gl)返回要render的vertex.
drawScene(gl);
}//main
</script>
webgl_helper.js
function drawScene(gl) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.clearStencil(0); // 用0填充 stencil buffer
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
const fieldOfView = 45 * Math.PI / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = -100.0;
const projectionMatrix = mat4.create();

本文是关于JavaScript WebGL2中蒙板(stencil test)技术的学习笔记,通过一个包含webgl.html、webgl_helper.js、shape.js和shader.js四个源文件的demo,展示蒙板的使用和实现效果。
最低0.47元/天 解锁文章
296

被折叠的 条评论
为什么被折叠?



