【发布时间】:2019-04-25 06:04:39
【问题描述】:
我正在尝试在画布上创建两个对象,一个八边形和一个金字塔。八角形的出现没有任何问题,但金字塔却没有。我附上金字塔的代码。
pyramidPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, pyramidPositionBuffer);
let pyramidVerts = [
0.0, 0.5, 0.0, //0
-0.5, 0.0, -0.5, //1
0.5, 0.0, -0.5, //2
0.5, 0.0, 0.5, //3
-0.5, 0.0, 0.5 //4
];
pyramidPositionBuffer.itemSize = 3;
pyramidPositionBuffer.numItems = 5;
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(pyramidVerts), gl.STATIC_DRAW);
pyramidColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, pyramidColorBuffer);
let pyramidColors = [
1.0, 1.0, 1.0, 1.0,
1.0, 0.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 1.0, 1.0
];
pyramidColorBuffer.itemSize = 4;
pyramidColorBuffer.numItems = 5;
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(pyramidColorBuffer),gl.STATIC_DRAWS);
pyramidIndexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, pyramidIndexBuffer);
let pyramidIndeces = [
0, 1, 2,
0, 2, 3,
0, 3, 4,
0, 4, 1
];
pyramidIndexBuffer.itemSize = 1;
pyramidIndexBuffer.numItems = 12;
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(pyramidIndeces), gl.STATIC_DRAW);
}
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);
mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [-1.5, 0.0, -6.5]); // We store a translation to our matrix, so when the first object is drawn it will be in that position.
// Connect the attributes with the shaders and draw...
gl.bindBuffer(gl.ARRAY_BUFFER,octagonPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, octagonPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, octagonColorBuffer);
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, octagonColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, octagonIndexBuffer);
setMatrixUniforms();
gl.drawElements(gl.TRIANGLES, octagonIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);
mat4.translate(mvMatrix, [2.8, 0.0, 0.0]);
gl.bindBuffer(gl.ARRAY_BUFFER,pyramidPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, pyramidPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, pyramidColorBuffer);
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, pyramidColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, pyramidIndexBuffer);
setMatrixUniforms();
gl.drawElements(gl.TRIANGLES, pyramidIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);
}
我用创建八边形的相同方式创建了金字塔,但由于某种原因它没有出现。如果我尝试画两次八边形,它没有问题。
【问题讨论】:
-
如果您花一些时间了解浏览器中的JavaScript console,它会告诉您这些错误。
标签: javascript html canvas webgl