Boilerplate 1 - Web APIs 编辑
{{IncludeSubnav("/en-US/Learn")}}
This example describes repeated pieces of code that will be hidden from now on, as well as defining a JavaScript utility function to make WebGL initialization easier.
Boilerplate code for setting up WebGL rendering context
By now you are quite used to seeing the same pieces of HTML, CSS, and JavaScript repeated again and again. So we are going to hide them from now on. This would allow us to focus on the interesting pieces of code that are most relevant for learning WebGL.
Specifically, the HTML has a <p>
element that contains some descriptive text about the page and may also hold error messages; a <canvas>
element; and optionally a <button>
. The CSS contains rules for body
, canvas
, and button
. Any additional non-trivial CSS and HTML will be displayed on the pages of specific examples.
In following examples, we will use a JavaScript helper function, getRenderingContext()
, to initialize the WebGL rendering context. By now, you should be able to understand what the function does. Basically, it gets the WebGL rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context. In case of error, it displays an error message and returns null
.
Finally, all JavaScript code will run within an immediate function, which is a common JavaScript technique (see Function). The function declaration and invocation will also be hidden.
HTML
<p>[ Some descriptive text about the example. ]</p>
<button>[ Optional button element. ]</button>
<canvas>Your browser does not seem to support
HTML5 canvas.</canvas>
CSS
body {
text-align : center;
}
canvas {
display : block;
width : 280px;
height : 210px;
margin : auto;
padding : 0;
border : none;
background-color : black;
}
button {
display : block;
font-size : inherit;
margin : auto;
padding : 0.6em;
}
JavaScript
function getRenderingContext() {
var canvas = document.querySelector("canvas");
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
var gl = canvas.getContext("webgl")
|| canvas.getContext("experimental-webgl");
if (!gl) {
var paragraph = document.querySelector("p");
paragraph.innerHTML = "Failed to get WebGL context."
+ "Your browser or device may not support WebGL.";
return null;
}
gl.viewport(0, 0,
gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
return gl;
}
The source code of this example is also available on GitHub.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论