我正在使用webgl创建各种游戏,并且第一页是用户可以选择要玩的角色的页面。用户可以从3种3D模型中进行选择,理想情况下,按钮“输入”必须清除画布并渲染整个新场景(或一组模型)。我似乎不知道该怎么做。
我最初想让玩家按下Enter键,它会加载另一个js文件,但我真的不知道该怎么做。我想到的另一种方法是清除画布并仅渲染所选模型。我尝试了多种方法,例如清理画布,甚至经历了提示我尝试的现有问题:
context.clearRect(0, 0, canvas.width, canvas.height);
但是没有任何作用。
重要的是要记住,WebGL的画布只是一个像素矩形,而WebGL本身只是绘制像素。如果您希望事物出现和消失,那完全取决于您的代码告诉WebGL要绘制哪些像素。 WebGL本身没有场景或模型的概念。
一个动画的WebGL页面通常是这样构造的
// at init time
create various shaders programs
load and/or create vertex data for things we want to draw
load and/or create textures for things we want to draw
// at render time
loop with requestAnimationFrame
update the positions and orientation of things we want to draw
clear the canvas
draw the things we want drawn right now
注意,它是每帧清除画布。因此,没有模型可言。相反。模型只出现是因为代码绘制了它们。如果您不想显示特定的模型,请不要绘制它。
[如果您想现在绘制一些东西,以后再绘制其他东西,例如当玩家按下Enter键时,这完全取决于您。您要做的只是确定要画些什么。也许您设置了一个标志,
if (flag) {
draw banana
} else {
draw grapes
}
也许您将事物添加到数组中并删除其他事物
let listOfThingsToDraw = [];
if use pressed enter
// keep everything not a banana
listOfThingsToDraw = listOfThingsToDraw.filter(thing => !isBanana(thing));
// add 10 grapes
for (let i = 0; i < 10; ++i) {
listOfThingsToDraw.push(makeRandomGrapeThing());
}
}
并且在渲染循环中绘制listOfThingsToDraw
for (const thing of listOfThingsToDraw) {
gl.useProgram(programNeededForThing)
setup attributes for thing
set uniforms and bind textures for thing
draw thing
也许您已经预先准备好要绘制的事物列表,然后选择其他列表。
const monkeyList = [banana, banana, banana, monkey];
const beeList = [flower, flower, flower, bee];
let listOfThingsToDraw = monkeyList;
if user pressed enter
listOfThingsToDraw = beeList
其中没有一个与WebGL直接相关。 WebGL just draws points, lines, and triangles。其他一切都取决于您以及如何组织代码。
这里是an article on drawing multiple things和here's an article on scene graphs,这是组织绘画内容的常用方法。