diff --git a/files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.md b/files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.md index 92f33bbad49241..0c3f9a1b62207d 100644 --- a/files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.md +++ b/files/zh-cn/web/api/webgl_api/webgl_model_view_projection/index.md @@ -39,9 +39,8 @@ WebGL 空间中的点和多边形的个体转化由基本的转换矩阵(例 ```js function WebGLBox() { - // 设置 canvas 和 WebGL 上下文 - this.canvas = document.getElementById('canvas'); + this.canvas = document.getElementById("canvas"); this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; this.gl = MDN.createContext(canvas); @@ -49,17 +48,20 @@ function WebGLBox() { var gl = this.gl; // 设置一个 WebGL 程序,任何 MDN 对象相关的部分在本文之外定义 - this.webglProgram = MDN.createWebGLProgramFromIds(gl, 'vertex-shader', 'fragment-shader'); + this.webglProgram = MDN.createWebGLProgramFromIds( + gl, + "vertex-shader", + "fragment-shader", + ); gl.useProgram(this.webglProgram); // 保存 attribute 和 uniform 位置 - this.positionLocation = gl.getAttribLocation(this.webglProgram, 'position'); - this.colorLocation = gl.getUniformLocation(this.webglProgram, 'color'); + this.positionLocation = gl.getAttribLocation(this.webglProgram, "position"); + this.colorLocation = gl.getUniformLocation(this.webglProgram, "color"); // 告诉 WebGL 在绘制时测试深度,所以如果一个正方形后面有另一个正方形 // 另一个正方形不会被绘制 gl.enable(gl.DEPTH_TEST); - } ``` @@ -68,22 +70,32 @@ function WebGLBox() { 现在,我们将创建一个在屏幕上绘制框的方法。 ```js -WebGLBox.prototype.draw = function(settings) { - +WebGLBox.prototype.draw = function (settings) { // 创建一下 attribute 数据; 这些是最终绘制到屏幕上的三角形 // 有两个形成一个正方形 var data = new Float32Array([ - //Triangle 1 - settings.left, settings.bottom, settings.depth, - settings.right, settings.bottom, settings.depth, - settings.left, settings.top, settings.depth, + settings.left, + settings.bottom, + settings.depth, + settings.right, + settings.bottom, + settings.depth, + settings.left, + settings.top, + settings.depth, //Triangle 2 - settings.left, settings.top, settings.depth, - settings.right, settings.bottom, settings.depth, - settings.right, settings.top, settings.depth + settings.left, + settings.top, + settings.depth, + settings.right, + settings.bottom, + settings.depth, + settings.right, + settings.top, + settings.depth, ]); // 使用 WebGL 将其绘制到屏幕上 @@ -107,7 +119,7 @@ WebGLBox.prototype.draw = function(settings) { // 在屏幕上绘制该三角形 gl.drawArrays(gl.TRIANGLES, 0, 6); -} +}; ``` 着色器是用 GLSL 编写的代码片段,它接收我们的点数据并最终将它们渲染到屏幕上。为了方便起见,这些着色器存储在 {{htmlelement("script")}} 元素之中,该元素通过自定义函数 `MDN.createWebGLProgramFromIds()` 引入程序中。这个方法是为这些教程编写的 [实用函数](https://github.com/TatumCreative/mdn-webgl) 集合的一部分,此处不再赘述。此函数用于处理获取一些 GLSL 源代码并将其编译为 WebGL 程序的基础操作。该函数具有三个参数 - 用于渲染程序的上下文,包含顶点着色器的 {{htmlelement("script")}} 元素的 ID 和包含片段着色器的 {{htmlelement("script")}} 元素的 ID。顶点着色器放置顶点,片段着色器为每个像素着色。 @@ -146,14 +158,13 @@ var box = new WebGLBox(); ```js box.draw({ + top: 0.5, // x + bottom: -0.5, // x + left: -0.5, // y + right: 0.5, // y - top : 0.5, // x - bottom : -0.5, // x - left : -0.5, // y - right : 0.5, // y - - depth : 0, // z - color : [1, 0.4, 0.4, 1] // red + depth: 0, // z + color: [1, 0.4, 0.4, 1], // red }); ``` @@ -161,14 +172,13 @@ box.draw({ ```js box.draw({ + top: 0.9, // x + bottom: 0, // x + left: -0.9, // y + right: 0.9, // y - top : 0.9, // x - bottom : 0, // x - left : -0.9, // y - right : 0.9, // y - - depth : 0.5, // z - color : [0.4, 1, 0.4, 1] // green + depth: 0.5, // z + color: [0.4, 1, 0.4, 1], // green }); ``` @@ -176,14 +186,13 @@ box.draw({ ```js box.draw({ + top: 1, // x + bottom: -1, // x + left: -1, // y + right: 1, // y - top : 1, // x - bottom : -1, // x - left : -1, // y - right : 1, // y - - depth : -1.5, // z - color : [0.4, 0.4, 1, 1] // blue + depth: -1.5, // z + color: [0.4, 0.4, 1, 1], // blue }); ``` @@ -213,7 +222,6 @@ gl_Position = vec4(position, 1.0); ```js function cartesianToHomogeneous(point) { - var x = point[0]; var y = point[1]; var z = point[2]; @@ -222,13 +230,12 @@ function cartesianToHomogeneous(point) { } function homogeneousToCartesian(point) { - var x = point[0]; var y = point[1]; var z = point[2]; var w = point[3]; - return [x/w, y/w, z/w]; + return [x / w, y / w, z / w]; } ``` @@ -253,16 +260,33 @@ homogeneousToCartesian([10, 4, 5, 0]); ```js // 重新定义三角形以使用 W 分量 var data = new Float32Array([ - //Triangle 1 - settings.left, settings.bottom, settings.depth, settings.w, - settings.right, settings.bottom, settings.depth, settings.w, - settings.left, settings.top, settings.depth, settings.w, + settings.left, + settings.bottom, + settings.depth, + settings.w, + settings.right, + settings.bottom, + settings.depth, + settings.w, + settings.left, + settings.top, + settings.depth, + settings.w, //Triangle 2 - settings.left, settings.top, settings.depth, settings.w, - settings.right, settings.bottom, settings.depth, settings.w, - settings.right, settings.top, settings.depth, settings.w + settings.left, + settings.top, + settings.depth, + settings.w, + settings.right, + settings.bottom, + settings.depth, + settings.w, + settings.right, + settings.top, + settings.depth, + settings.w, ]); ``` @@ -280,15 +304,14 @@ void main() { ```js box.draw({ - - top : 0.5, // x - bottom : -0.5, // x - left : -0.5, // y - right : 0.5, // y - w : 0.7, // w - 放大这个盒子 - - depth : 0, // z - color : [1, 0.4, 0.4, 1] // red + top: 0.5, // x + bottom: -0.5, // x + left: -0.5, // y + right: 0.5, // y + w: 0.7, // w - 放大这个盒子 + + depth: 0, // z + color: [1, 0.4, 0.4, 1], // red }); ``` @@ -296,15 +319,14 @@ box.draw({ ```js box.draw({ - - top : 0.9, // x - bottom : 0, // x - left : -0.9, // y - right : 0.9, // y - w : 1.1, // w - 缩小这个盒子 - - depth : 0.5, // z - color : [0.4, 1, 0.4, 1] // green + top: 0.9, // x + bottom: 0, // x + left: -0.9, // y + right: 0.9, // y + w: 1.1, // w - 缩小这个盒子 + + depth: 0.5, // z + color: [0.4, 1, 0.4, 1], // green }); ``` @@ -312,15 +334,14 @@ box.draw({ ```js box.draw({ - - top : 1, // x - bottom : -1, // x - left : -1, // y - right : 1, // y - w : 1.5, // w - 把这个盒子带回范围内 - - depth : -1.5, // z - color : [0.4, 0.4, 1, 1] // blue + top: 1, // x + bottom: -1, // x + left: -1, // y + right: 1, // y + w: 1.5, // w - 把这个盒子带回范围内 + + depth: -1.5, // z + color: [0.4, 0.4, 1, 1], // blue }); ``` @@ -346,8 +367,7 @@ box.draw({ 以下代码示例在 `CubeDemo` 对象上定义了一个创建模型矩阵的方法。它使用了自定义函数来创建和乘以 [MDN WebGL](https://github.com/TatumCreative/mdn-webgl) 共享代码中定义的矩阵。新的函数如下: ```js -CubeDemo.prototype.computeModelMatrix = function(now) { - +CubeDemo.prototype.computeModelMatrix = function (now) { // 缩小 50% var scale = MDN.scaleMatrix(0.5, 0.5, 0.5); @@ -363,9 +383,9 @@ CubeDemo.prototype.computeModelMatrix = function(now) { // 相乘,确定以相反的顺序读取它们 this.transforms.model = MDN.multiplyArrayOfMatrices([ position, // step 4 - rotateY, // step 3 - rotateX, // step 2 - scale // step 1 + rotateY, // step 3 + rotateX, // step 2 + scale, // step 1 ]); }; ``` @@ -373,13 +393,17 @@ CubeDemo.prototype.computeModelMatrix = function(now) { 为了在着色器中使用它,必须将其设置在 uniforms 的位置。uniforms 的位置保存在 `locations` 对象中,如下所示: ```js -this.locations.model = gl.getUniformLocation(webglProgram, 'model'); +this.locations.model = gl.getUniformLocation(webglProgram, "model"); ``` 最后,将 uniforms 设置在那个位置,这就把矩阵交给了 GPU。 ```js -gl.uniformMatrix4fv(this.locations.model, false, new Float32Array(this.transforms.model)); +gl.uniformMatrix4fv( + this.locations.model, + false, + new Float32Array(this.transforms.model), +); ``` 在着色器中,每个位置顶点首先被转换为齐次坐标(vec4 对象),然后与模型矩阵相乘。 @@ -445,12 +469,7 @@ gl_Position = vec4(transformedPosition.xyz, w); 填充 w 分量的最后一步实际上可以用一个简单的矩阵完成。从 identity 矩阵开始: ```js -var identity = [ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1, -]; +var identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; MDN.multiplyPoint(identity, [2, 3, 4, 1]); //> [2, 3, 4, 1] @@ -459,12 +478,7 @@ MDN.multiplyPoint(identity, [2, 3, 4, 1]); 然后将最后一列的 1 向上移动一个空格。 ```js -var copyZ = [ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 1, - 0, 0, 0, 0, -]; +var copyZ = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]; MDN.multiplyPoint(copyZ, [2, 3, 4, 1]); //> [2, 3, 4, 4] @@ -489,22 +503,22 @@ MDN.multiplyPoint(simpleProjection, [2, 3, 4, 1]); 进一步展开我们可以看到它是如何工作的: ```js -var x = (2 * 1) + (3 * 0) + (4 * 0) + (1 * 0) -var y = (2 * 0) + (3 * 1) + (4 * 0) + (1 * 0) -var z = (2 * 0) + (3 * 0) + (4 * 1) + (1 * 0) -var w = (2 * 0) + (3 * 0) + (4 * scaleFactor) + (1 * scaleFactor) +var x = 2 * 1 + 3 * 0 + 4 * 0 + 1 * 0; +var y = 2 * 0 + 3 * 1 + 4 * 0 + 1 * 0; +var z = 2 * 0 + 3 * 0 + 4 * 1 + 1 * 0; +var w = 2 * 0 + 3 * 0 + 4 * scaleFactor + 1 * scaleFactor; ``` 最后一行可以简化为: ```js -w = (4 * scaleFactor) + (1 * scaleFactor) +w = 4 * scaleFactor + 1 * scaleFactor; ``` 然后将 scaleFactor 提取出来,我们得到: ```js -w = (4 + 1) * scaleFactor +w = (4 + 1) * scaleFactor; ``` 这与我们在前面示例中使用的 `(z + 1) * scaleFactor` 完全相同。 @@ -512,15 +526,25 @@ w = (4 + 1) * scaleFactor 在 box demo 中,添加了一个额外的 `.computeSimpleProjectionMatrix()` 方法。在 `.draw()` 方法中调用,并将比例因子传递给它。结果应该与上一个示例相同: ```js -CubeDemo.prototype.computeSimpleProjectionMatrix = function(scaleFactor) { - +CubeDemo.prototype.computeSimpleProjectionMatrix = function (scaleFactor) { this.transforms.projection = [ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, scaleFactor, - 0, 0, 0, scaleFactor + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + scaleFactor, + 0, + 0, + 0, + scaleFactor, ]; - }; ``` @@ -554,18 +578,34 @@ gl_Position = projection * model * vec4(position, 1.0); 让我们看一下 `perspectiveMatrix()` 函数,该函数计算了透视矩阵。 ```js -MDN.perspectiveMatrix = function(fieldOfViewInRadians, aspectRatio, near, far) { - +MDN.perspectiveMatrix = function ( + fieldOfViewInRadians, + aspectRatio, + near, + far, +) { var f = 1.0 / Math.tan(fieldOfViewInRadians / 2); var rangeInv = 1 / (near - far); return [ - f / aspectRatio, 0, 0, 0, - 0, f, 0, 0, - 0, 0, (near + far) * rangeInv, -1, - 0, 0, near * far * rangeInv * 2, 0 + f / aspectRatio, + 0, + 0, + 0, + 0, + f, + 0, + 0, + 0, + 0, + (near + far) * rangeInv, + -1, + 0, + 0, + near * far * rangeInv * 2, + 0, ]; -} +}; ``` 此函数的四个参数是: @@ -581,8 +621,7 @@ MDN.perspectiveMatrix = function(fieldOfViewInRadians, aspectRatio, near, far) { 在最新版本的盒子 demo 中, `computeSimpleProjectionMatrix()` 函数已替换为 `computePerspectiveMatrix()` 函数。 ```js -CubeDemo.prototype.computePerspectiveMatrix = function() { - +CubeDemo.prototype.computePerspectiveMatrix = function () { var fieldOfViewInRadians = Math.PI * 0.5; var aspectRatio = window.innerWidth / window.innerHeight; var nearClippingPlaneDistance = 1; @@ -592,7 +631,7 @@ CubeDemo.prototype.computePerspectiveMatrix = function() { fieldOfViewInRadians, aspectRatio, nearClippingPlaneDistance, - farClippingPlaneDistance + farClippingPlaneDistance, ); }; ``` @@ -641,19 +680,17 @@ gl_Position = projection * model * vec4(position, 1.0); 以下的 `computeViewMatrix()` 函数通过向内和向外,向左和向右移动的视图矩阵来激活视图矩阵。 ```js -CubeDemo.prototype.computeViewMatrix = function(now) { - +CubeDemo.prototype.computeViewMatrix = function (now) { var moveInAndOut = 20 * Math.sin(now * 0.002); var moveLeftAndRight = 15 * Math.sin(now * 0.0017); // 各个方向移动相机 - var position = MDN.translateMatrix(moveLeftAndRight, 0, 50 + moveInAndOut ); + var position = MDN.translateMatrix(moveLeftAndRight, 0, 50 + moveInAndOut); // 相乘,确保以相反的顺序读取它们 var matrix = MDN.multiplyArrayOfMatrices([ - // 练习:旋转相机的视角 - position + position, ]); // 翻转相机的运动操作,因为我们实际上是 diff --git a/files/zh-cn/web/api/webgl_lose_context/index.md b/files/zh-cn/web/api/webgl_lose_context/index.md index 948bf2e2cadb22..f0061d1774ba2a 100644 --- a/files/zh-cn/web/api/webgl_lose_context/index.md +++ b/files/zh-cn/web/api/webgl_lose_context/index.md @@ -23,14 +23,18 @@ WebGL 扩展可以通过 {{domxref("WebGLRenderingContext.getExtension()")}} 方 使用这个扩展,你可以模拟 [`webglcontextlost`](/zh-CN/docs/Web/API/HTMLCanvasElement/webglcontextlost_event) 和 [`webglcontextrestored`](/zh-CN/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event) 事件: ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); - -canvas.addEventListener('webglcontextlost', function(e) { - console.log(e); -}, false); - -gl.getExtension('WEBGL_lose_context').loseContext(); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); + +canvas.addEventListener( + "webglcontextlost", + function (e) { + console.log(e); + }, + false, +); + +gl.getExtension("WEBGL_lose_context").loseContext(); // 打印了 "webglcontextlost" 类型的 WebGLContextEvent 事件。 ``` diff --git a/files/zh-cn/web/api/webgl_lose_context/losecontext/index.md b/files/zh-cn/web/api/webgl_lose_context/losecontext/index.md index a86460d2873faa..4914450191ac2c 100644 --- a/files/zh-cn/web/api/webgl_lose_context/losecontext/index.md +++ b/files/zh-cn/web/api/webgl_lose_context/losecontext/index.md @@ -20,14 +20,18 @@ gl.getExtension('WEBGL_lose_context').loseContext(); 你可以用这个方法模拟 [`webglcontextlost`](/zh-CN/docs/Web/API/HTMLCanvasElement/webglcontextlost_event) 事件: ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); - -canvas.addEventListener('webglcontextlost', function(e) { - console.log(e); -}, false); - -gl.getExtension('WEBGL_lose_context').loseContext(); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); + +canvas.addEventListener( + "webglcontextlost", + function (e) { + console.log(e); + }, + false, +); + +gl.getExtension("WEBGL_lose_context").loseContext(); // webglcontextlost 事件被触发。 ``` diff --git a/files/zh-cn/web/api/webgl_lose_context/restorecontext/index.md b/files/zh-cn/web/api/webgl_lose_context/restorecontext/index.md index 1fc5091e4caf7f..a5ab54b2714208 100644 --- a/files/zh-cn/web/api/webgl_lose_context/restorecontext/index.md +++ b/files/zh-cn/web/api/webgl_lose_context/restorecontext/index.md @@ -22,14 +22,18 @@ gl.getExtension('WEBGL_lose_context').restoreContext(); 你可以用这个方法模拟 [`webglcontextrestored`](/zh-CN/docs/Web/API/HTMLCanvasElement/webglcontextrestored_event) 事件: ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); - -canvas.addEventListener('webglcontextrestored', function(e) { - console.log(e); -}, false); - -gl.getExtension('WEBGL_lose_context').restoreContext(); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); + +canvas.addEventListener( + "webglcontextrestored", + function (e) { + console.log(e); + }, + false, +); + +gl.getExtension("WEBGL_lose_context").restoreContext(); ``` ## 规范 diff --git a/files/zh-cn/web/api/webglbuffer/index.md b/files/zh-cn/web/api/webglbuffer/index.md index c9b9176fdee236..6767ab04e86346 100644 --- a/files/zh-cn/web/api/webglbuffer/index.md +++ b/files/zh-cn/web/api/webglbuffer/index.md @@ -21,8 +21,8 @@ slug: Web/API/WebGLBuffer ### 创建一个缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var buffer = gl.createBuffer(); ``` diff --git a/files/zh-cn/web/api/webglcontextevent/index.md b/files/zh-cn/web/api/webglcontextevent/index.md index 0eb9f0b1c44ca4..8e832f3b38e246 100644 --- a/files/zh-cn/web/api/webglcontextevent/index.md +++ b/files/zh-cn/web/api/webglcontextevent/index.md @@ -29,14 +29,18 @@ _此接口本身并没有定义任何方法,而是从它的父接口 {{domxref 使用 {{domxref("WEBGL_lose_context")}} 插件,你可以模拟 {{domxref("HTMLCanvasElement/webglcontextlost_event", "webglcontextlost")}} 和 {{domxref("HTMLCanvasElement/webglcontextrestored_event", "webglcontextrestored")}} 事件: ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); - -canvas.addEventListener('webglcontextlost', function(e) { - console.log(e); -}, false); - -gl.getExtension('WEBGL_lose_context').loseContext(); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); + +canvas.addEventListener( + "webglcontextlost", + function (e) { + console.log(e); + }, + false, +); + +gl.getExtension("WEBGL_lose_context").loseContext(); // 记录了 "webglcontextlost" 类型的 WebGLContextEvent 事件 ``` diff --git a/files/zh-cn/web/api/webglframebuffer/index.md b/files/zh-cn/web/api/webglframebuffer/index.md index b59444fb3d03ef..f15bf4ddc95545 100644 --- a/files/zh-cn/web/api/webglframebuffer/index.md +++ b/files/zh-cn/web/api/webglframebuffer/index.md @@ -21,8 +21,8 @@ slug: Web/API/WebGLFramebuffer ### 创建一个帧缓冲 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var buffer = gl.createFramebuffer(); ``` diff --git a/files/zh-cn/web/api/webglprogram/index.md b/files/zh-cn/web/api/webglprogram/index.md index e890f4be2869d9..d9706977b5f4d3 100644 --- a/files/zh-cn/web/api/webglprogram/index.md +++ b/files/zh-cn/web/api/webglprogram/index.md @@ -18,9 +18,9 @@ gl.attachShader(program, fragmentShader); gl.linkProgram(program); -if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) { +if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var info = gl.getProgramInfoLog(program); - throw 'WebGL program 不能编译。\n\n' + info; + throw "WebGL program 不能编译。\n\n" + info; } ``` diff --git a/files/zh-cn/web/api/webglrenderbuffer/index.md b/files/zh-cn/web/api/webglrenderbuffer/index.md index 50aca051f614c8..d56e5de4652b83 100644 --- a/files/zh-cn/web/api/webglrenderbuffer/index.md +++ b/files/zh-cn/web/api/webglrenderbuffer/index.md @@ -21,8 +21,8 @@ slug: Web/API/WebGLRenderbuffer ### 创建一个 render buffer 对象 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var buffer = gl.createRenderbuffer(); ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/attachshader/index.md b/files/zh-cn/web/api/webglrenderingcontext/attachshader/index.md index eff777435d9e4d..ee2c15bbd051c7 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/attachshader/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/attachshader/index.md @@ -33,7 +33,7 @@ gl.attachShader(program, fragmentShader); gl.linkProgram(program); -if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) { +if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var info = gl.getProgramInfoLog(program); throw "Could not compile WebGL program. \n\n" + info; } diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.md index 46c517101b7e28..7a401cb1c0cf9e 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/bindbuffer/index.md @@ -48,8 +48,8 @@ void gl.bindBuffer(target, buffer); ### 将缓冲区绑定到目标 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.md index 085b365b0d8b57..e17afec8069f3c 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/bindframebuffer/index.md @@ -41,8 +41,8 @@ None. ### 绑定帧缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.md index 92963a7345ff6c..e5c3563a4a46b7 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/bindrenderbuffer/index.md @@ -37,8 +37,8 @@ None. ### 绑定一个渲染缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var renderbuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); diff --git a/files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.md b/files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.md index 55d5d92f36135f..453ebf23a72363 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/bindtexture/index.md @@ -42,8 +42,8 @@ void gl.bindTexture(target, texture); ### 绑定纹理 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); diff --git a/files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.md b/files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.md index dedf944153d423..fb746f41af3084 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/bufferdata/index.md @@ -76,8 +76,8 @@ None. ### 使用 `bufferData` ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW); diff --git a/files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.md b/files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.md index 52dbb25da35288..1cf7c19318f297 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/compressedteximage2d/index.md @@ -150,15 +150,22 @@ None. ## Examples ```js -var ext = ( - gl.getExtension('WEBGL_compressed_texture_s3tc') || - gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || - gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc') -); +var ext = + gl.getExtension("WEBGL_compressed_texture_s3tc") || + gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || + gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); -gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA_S3TC_DXT5_EXT, 512, 512, 0, textureData); +gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + ext.COMPRESSED_RGBA_S3TC_DXT5_EXT, + 512, + 512, + 0, + textureData, +); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.md index 2b25ec8623dd21..3c120985a722c8 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/createbuffer/index.md @@ -26,8 +26,8 @@ WebGLBuffer gl.createBuffer(); ### 创建一个缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var buffer = gl.createBuffer(); ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.md index 15047db8622400..e9b05ef92c274a 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/createframebuffer/index.md @@ -24,8 +24,8 @@ None. ### 创建一个帧缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var framebuffer = gl.createFramebuffer(); ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/createprogram/index.md b/files/zh-cn/web/api/webglrenderingcontext/createprogram/index.md index cc30e330ef8580..e7fb709a97882d 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/createprogram/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/createprogram/index.md @@ -34,7 +34,7 @@ gl.attachShader(program, fragmentShader); gl.linkProgram(program); -if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) { +if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var info = gl.getProgramInfoLog(program); throw "Could not compile WebGL program. \n\n" + info; } diff --git a/files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.md index b3ebe11fd2ea62..c8a24d247eb8fa 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/createrenderbuffer/index.md @@ -26,8 +26,8 @@ None. ### 创建一个渲染缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var renderBuffer = gl.createRenderBuffer(); ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/createtexture/index.md b/files/zh-cn/web/api/webglrenderingcontext/createtexture/index.md index 6f6548995f17e1..ef7267e11b48ab 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/createtexture/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/createtexture/index.md @@ -28,8 +28,8 @@ WebGLTexture gl.createTexture(); ### 创建一个纹理 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var texture = gl.createTexture(); ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.md index ffbae242642bd4..f4cbd980c378ba 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/deletebuffer/index.md @@ -27,8 +27,8 @@ None. ### 删除一个 buffer ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var buffer = gl.createBuffer(); // ... diff --git a/files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.md index dfc719414e2ddc..4b8566ea28021b 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/deleteframebuffer/index.md @@ -27,8 +27,8 @@ None. ### 删除一个帧缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var framebuffer = gl.createFramebuffer(); // ... diff --git a/files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.md b/files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.md index abce77c4084a54..ca50d9a1fd192b 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/deleteprogram/index.md @@ -27,8 +27,8 @@ None. ### 删除一个程序 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var program = gl.createProgram(); // ... diff --git a/files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.md b/files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.md index 2c3a6c6b0b42df..530749eba3410b 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/deleterenderbuffer/index.md @@ -27,8 +27,8 @@ None. ### 删除一个渲染缓冲区 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var renderbuffer = gl.createRenderbuffer(); // ... diff --git a/files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.md b/files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.md index 3a379cd810c700..5cc1608c9686d4 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/deletetexture/index.md @@ -25,8 +25,8 @@ void gl.deleteTexture(texture); ### Deleting a texture ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var texture = gl.createTexture(); // ... diff --git a/files/zh-cn/web/api/webglrenderingcontext/disable/index.md b/files/zh-cn/web/api/webglrenderingcontext/disable/index.md index 04ed7af8891d4c..a745b55c64c79b 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/disable/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/disable/index.md @@ -19,17 +19,17 @@ void gl.disable(cap); - : A {{domxref("GLenum")}} specifying which WebGL capability to disable. Possible values: - | Constant | Description | - | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | - | `gl.BLEND` | Deactivates blending of the computed fragment color values. See {{domxref("WebGLRenderingContext.blendFunc()")}}. | - | `gl.CULL_FACE` | Deactivates culling of polygons. See {{domxref("WebGLRenderingContext.cullFace()")}}. | - | `gl.DEPTH_TEST` | Deactivates depth comparisons and updates to the depth buffer. See {{domxref("WebGLRenderingContext.depthFunc()")}}. | - | `gl.DITHER` | Deactivates dithering of color components before they get written to the color buffer. | - | `gl.POLYGON_OFFSET_FILL` | Deactivates adding an offset to depth values of polygon's fragments. See {{domxref("WebGLRenderingContext.polygonOffset()")}}. | - | `gl.SAMPLE_ALPHA_TO_COVERAGE` | Deactivates the computation of a temporary coverage value determined by the alpha value. | - | `gl.SAMPLE_COVERAGE` | Deactivates ANDing the fragment's coverage with the temporary coverage value. See {{domxref("WebGLRenderingContext.sampleCoverage()")}}. | + | Constant | Description | + | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | + | `gl.BLEND` | Deactivates blending of the computed fragment color values. See {{domxref("WebGLRenderingContext.blendFunc()")}}. | + | `gl.CULL_FACE` | Deactivates culling of polygons. See {{domxref("WebGLRenderingContext.cullFace()")}}. | + | `gl.DEPTH_TEST` | Deactivates depth comparisons and updates to the depth buffer. See {{domxref("WebGLRenderingContext.depthFunc()")}}. | + | `gl.DITHER` | Deactivates dithering of color components before they get written to the color buffer. | + | `gl.POLYGON_OFFSET_FILL` | Deactivates adding an offset to depth values of polygon's fragments. See {{domxref("WebGLRenderingContext.polygonOffset()")}}. | + | `gl.SAMPLE_ALPHA_TO_COVERAGE` | Deactivates the computation of a temporary coverage value determined by the alpha value. | + | `gl.SAMPLE_COVERAGE` | Deactivates ANDing the fragment's coverage with the temporary coverage value. See {{domxref("WebGLRenderingContext.sampleCoverage()")}}. | | `gl.SCISSOR_TEST` | Deactivates the scissor test that discards fragments that are outside of the scissor rectangle. See {{domxref("WebGLRenderingContext.scissor()")}}. | - | `gl.STENCIL_TEST` | Deactivates stencil testing and updates to the stencil buffer. See {{domxref("WebGLRenderingContext.stencilFunc()")}}. | + | `gl.STENCIL_TEST` | Deactivates stencil testing and updates to the stencil buffer. See {{domxref("WebGLRenderingContext.stencilFunc()")}}. | When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally: diff --git a/files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.md b/files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.md index a315d2aaf162be..3e2c046bebaf40 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/drawingbufferwidth/index.md @@ -24,8 +24,8 @@ gl.drawingBufferWidth; 你可以通过下面几行代码来获取绘图缓冲区的宽度: ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); gl.drawingBufferWidth; // 300 ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/enable/index.md b/files/zh-cn/web/api/webglrenderingcontext/enable/index.md index 53bc2e021586e8..7d9285d33f3faa 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/enable/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/enable/index.md @@ -17,17 +17,17 @@ void gl.enable(cap);参数 - : 让 WebGL 开启某种特性,可能的值: - | Constant | Description | - | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ | - | `gl.BLEND` | 激活片元的颜色融合计算。参见 {{domxref("WebGLRenderingContext.blendFunc()")}}. | - | `gl.CULL_FACE` | 激活多边形正反面剔除。参见{{domxref("WebGLRenderingContext.cullFace()")}}. | - | `gl.DEPTH_TEST` | 激活深度比较,并且更新深度缓冲区。参见{{domxref("WebGLRenderingContext.depthFunc()")}}. | - | `gl.DITHER` | 激活在写入颜色缓冲区之前,抖动颜色成分。 | - | `gl.POLYGON_OFFSET_FILL` | 激活添加多边形片段的深度值偏移。参见{{domxref("WebGLRenderingContext.polygonOffset()")}}. | - | `gl.SAMPLE_ALPHA_TO_COVERAGE` | 激活通过 alpha 值决定的临时覆盖值计算。(抗锯齿) | + | Constant | Description | + | ----------------------------- | ----------------------------------------------------------------------------------------------------- | + | `gl.BLEND` | 激活片元的颜色融合计算。参见 {{domxref("WebGLRenderingContext.blendFunc()")}}. | + | `gl.CULL_FACE` | 激活多边形正反面剔除。参见{{domxref("WebGLRenderingContext.cullFace()")}}. | + | `gl.DEPTH_TEST` | 激活深度比较,并且更新深度缓冲区。参见{{domxref("WebGLRenderingContext.depthFunc()")}}. | + | `gl.DITHER` | 激活在写入颜色缓冲区之前,抖动颜色成分。 | + | `gl.POLYGON_OFFSET_FILL` | 激活添加多边形片段的深度值偏移。参见{{domxref("WebGLRenderingContext.polygonOffset()")}}. | + | `gl.SAMPLE_ALPHA_TO_COVERAGE` | 激活通过 alpha 值决定的临时覆盖值计算。(抗锯齿) | | `gl.SAMPLE_COVERAGE` | 激活使用临时覆盖值,位和运算片段的覆盖值。参见 {{domxref("WebGLRenderingContext.sampleCoverage()")}}. | - | `gl.SCISSOR_TEST` | 激活剪裁测试,即丢弃在剪裁矩形范围外的片段。{{domxref("WebGLRenderingContext.scissor()")}}. | - | `gl.STENCIL_TEST` | 激活模板测试并且更新模板缓冲区。参见{{domxref("WebGLRenderingContext.stencilFunc()")}}. | + | `gl.SCISSOR_TEST` | 激活剪裁测试,即丢弃在剪裁矩形范围外的片段。{{domxref("WebGLRenderingContext.scissor()")}}. | + | `gl.STENCIL_TEST` | 激活模板测试并且更新模板缓冲区。参见{{domxref("WebGLRenderingContext.stencilFunc()")}}. | 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}时,可以添加使用下面的值。 diff --git a/files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.md b/files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.md index 0c4d454617f428..a311cfb5fc6892 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/enablevertexattribarray/index.md @@ -42,12 +42,17 @@ void gl.enableVertexAttribArray(index); ```js gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); -aVertexPosition = - gl.getAttribLocation(shaderProgram, "aVertexPosition"); +aVertexPosition = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(aVertexPosition); -gl.vertexAttribPointer(aVertexPosition, vertexNumComponents, - gl.FLOAT, false, 0, 0); +gl.vertexAttribPointer( + aVertexPosition, + vertexNumComponents, + gl.FLOAT, + false, + 0, + 0, +); gl.drawArrays(gl.TRIANGLES, 0, vertexCount); ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.md b/files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.md index 2fc3272c2952c8..eef04a212c1b5e 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/getattriblocation/index.md @@ -27,7 +27,7 @@ GLint gl.getAttribLocation(program, name); ## 示例 ```js -gl.getAttribLocation(program, 'vColor'); +gl.getAttribLocation(program, "vColor"); ``` ## 规范 diff --git a/files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.md b/files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.md index e7887776f4c5f8..67b35925beb591 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/getcontextattributes/index.md @@ -28,8 +28,8 @@ gl.getContextAttributes(); 和给定 WebGL 上下文 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); gl.getContextAttributes(); ``` @@ -50,9 +50,7 @@ gl.getContextAttributes(); 上下文的属性可以在用 {{domxref("HTMLCanvasElement.getContext()")}} 方法创建上下文时设置: ```js -canvas.getContext('webgl', - { antialias: false, - depth: false }); +canvas.getContext("webgl", { antialias: false, depth: false }); ``` 有关各个属性的更多信息,请参阅 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}}。 diff --git a/files/zh-cn/web/api/webglrenderingcontext/getextension/index.md b/files/zh-cn/web/api/webglrenderingcontext/getextension/index.md index 17c4222ad04ce6..92457c9447fb96 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/getextension/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/getextension/index.md @@ -27,10 +27,10 @@ gl.getExtension(name); 当一个 WebGL 扩展被启用后,就可以使用该扩展提供的方法、属性和常量。 ```js -var canvas = document.getElementById('canvas'); -gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +gl = canvas.getContext("webgl"); -gl.getExtension('WEBGL_lose_context').loseContext(); +gl.getExtension("WEBGL_lose_context").loseContext(); ``` ## WebGL 扩展 diff --git a/files/zh-cn/web/api/webglrenderingcontext/getparameter/index.md b/files/zh-cn/web/api/webglrenderingcontext/getparameter/index.md index e4cf779d3abd79..82e0c511936929 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/getparameter/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/getparameter/index.md @@ -610,81 +610,81 @@ any gl.getParameter(pname); 使用 {{domxref("WebGL2RenderingContext")}} 时,您可以查询以下 `pname` 参数。 -| 常量 | 返回类型 | 描述 | -| -------------------------------------------------- | ------------------------------------------------ | ---- | -| `gl.COPY_READ_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | -| `gl.COPY_WRITE_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | -| `gl.DRAW_BUFFERi` | {{domxref("GLenum")}} | | -| `gl.DRAW_FRAMEBUFFER_BINDING` | {{domxref("WebGLFramebuffer")}} | | -| `gl.FRAGMENT_SHADER_DERIVATIVE_HINT` | {{domxref("GLenum")}} | | -| `gl.MAX_3D_TEXTURE_SIZE` | {{domxref("GLint")}} | | -| `gl.MAX_ARRAY_TEXTURE_LAYERS` | {{domxref("GLint")}} | | -| `gl.MAX_CLIENT_WAIT_TIMEOUT_WEBGL` | {{domxref("GLint64")}} | | -| `gl.MAX_COLOR_ATTACHMENTS` | {{domxref("GLint")}} | | -| `gl.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS` | {{domxref("GLint64")}} | | -| `gl.MAX_COMBINED_UNIFORM_BLOCKS` | {{domxref("GLint")}} | | -| `gl.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS` | {{domxref("GLint64")}} | | -| `gl.MAX_DRAW_BUFFERS` | {{domxref("GLint")}} | | -| `gl.MAX_ELEMENT_INDEX` | {{domxref("GLint64")}} | | -| `gl.MAX_ELEMENTS_INDICES` | {{domxref("GLint")}} | | -| `gl.MAX_ELEMENTS_VERTICES` | {{domxref("GLint")}} | | -| `gl.MAX_FRAGMENT_INPUT_COMPONENTS` | {{domxref("GLint")}} | | -| `gl.MAX_FRAGMENT_UNIFORM_BLOCKS` | {{domxref("GLint")}} | | -| `gl.MAX_FRAGMENT_UNIFORM_COMPONENTS` | {{domxref("GLint")}} | | -| `gl.MAX_PROGRAM_TEXEL_OFFSET` | {{domxref("GLint")}} | | -| `gl.MAX_SAMPLES` | {{domxref("GLint")}} | | -| `gl.MAX_SERVER_WAIT_TIMEOUT` | {{domxref("GLint64")}} | | -| `gl.MAX_TEXTURE_LOD_BIAS` | {{domxref("GLfloat")}} | | -| `gl.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS` | {{domxref("GLint")}} | | -| `gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS` | {{domxref("GLint")}} | | -| `gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS` | {{domxref("GLint")}} | | -| `gl.MAX_UNIFORM_BLOCK_SIZE` | {{domxref("GLint64")}} | | -| `gl.MAX_UNIFORM_BUFFER_BINDINGS` | {{domxref("GLint")}} | | -| `gl.MAX_VARYING_COMPONENTS` | {{domxref("GLint")}} | | -| `gl.MAX_VERTEX_OUTPUT_COMPONENTS` | {{domxref("GLint")}} | | -| `gl.MAX_VERTEX_UNIFORM_BLOCKS` | {{domxref("GLint")}} | | -| `gl.MAX_VERTEX_UNIFORM_COMPONENTS` | {{domxref("GLint")}} | | -| `gl.MIN_PROGRAM_TEXEL_OFFSET` | {{domxref("GLint")}} | | -| `gl.PACK_ROW_LENGTH` | {{domxref("GLint")}} | | -| `gl.PACK_SKIP_PIXELS` | {{domxref("GLint")}} | | -| `gl.PACK_SKIP_ROWS` | {{domxref("GLint")}} | | -| `gl.PIXEL_PACK_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | -| `gl.PIXEL_UNPACK_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | -| `gl.RASTERIZER_DISCARD` | {{domxref("GLboolean")}} | | -| `gl.READ_BUFFER` | {{domxref("GLenum")}} | | -| `gl.READ_FRAMEBUFFER_BINDING` | {{domxref("WebGLFramebuffer")}} | | -| `gl.SAMPLE_ALPHA_TO_COVERAGE` | {{domxref("GLboolean")}} | | -| `gl.SAMPLE_COVERAGE` | {{domxref("GLboolean")}} | | -| `gl.SAMPLER_BINDING` | {{domxref("WebGLSampler")}} | | -| `gl.TEXTURE_BINDING_2D_ARRAY` | {{domxref("WebGLTexture")}} | | -| `gl.TEXTURE_BINDING_3D` | {{domxref("WebGLTexture")}} | | -| `gl.TRANSFORM_FEEDBACK_ACTIVE` | {{domxref("GLboolean")}} | | +| 常量 | 返回类型 | 描述 | +| -------------------------------------------------- | ------------------------------------- | ---- | +| `gl.COPY_READ_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | +| `gl.COPY_WRITE_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | +| `gl.DRAW_BUFFERi` | {{domxref("GLenum")}} | | +| `gl.DRAW_FRAMEBUFFER_BINDING` | {{domxref("WebGLFramebuffer")}} | | +| `gl.FRAGMENT_SHADER_DERIVATIVE_HINT` | {{domxref("GLenum")}} | | +| `gl.MAX_3D_TEXTURE_SIZE` | {{domxref("GLint")}} | | +| `gl.MAX_ARRAY_TEXTURE_LAYERS` | {{domxref("GLint")}} | | +| `gl.MAX_CLIENT_WAIT_TIMEOUT_WEBGL` | {{domxref("GLint64")}} | | +| `gl.MAX_COLOR_ATTACHMENTS` | {{domxref("GLint")}} | | +| `gl.MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS` | {{domxref("GLint64")}} | | +| `gl.MAX_COMBINED_UNIFORM_BLOCKS` | {{domxref("GLint")}} | | +| `gl.MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS` | {{domxref("GLint64")}} | | +| `gl.MAX_DRAW_BUFFERS` | {{domxref("GLint")}} | | +| `gl.MAX_ELEMENT_INDEX` | {{domxref("GLint64")}} | | +| `gl.MAX_ELEMENTS_INDICES` | {{domxref("GLint")}} | | +| `gl.MAX_ELEMENTS_VERTICES` | {{domxref("GLint")}} | | +| `gl.MAX_FRAGMENT_INPUT_COMPONENTS` | {{domxref("GLint")}} | | +| `gl.MAX_FRAGMENT_UNIFORM_BLOCKS` | {{domxref("GLint")}} | | +| `gl.MAX_FRAGMENT_UNIFORM_COMPONENTS` | {{domxref("GLint")}} | | +| `gl.MAX_PROGRAM_TEXEL_OFFSET` | {{domxref("GLint")}} | | +| `gl.MAX_SAMPLES` | {{domxref("GLint")}} | | +| `gl.MAX_SERVER_WAIT_TIMEOUT` | {{domxref("GLint64")}} | | +| `gl.MAX_TEXTURE_LOD_BIAS` | {{domxref("GLfloat")}} | | +| `gl.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS` | {{domxref("GLint")}} | | +| `gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS` | {{domxref("GLint")}} | | +| `gl.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS` | {{domxref("GLint")}} | | +| `gl.MAX_UNIFORM_BLOCK_SIZE` | {{domxref("GLint64")}} | | +| `gl.MAX_UNIFORM_BUFFER_BINDINGS` | {{domxref("GLint")}} | | +| `gl.MAX_VARYING_COMPONENTS` | {{domxref("GLint")}} | | +| `gl.MAX_VERTEX_OUTPUT_COMPONENTS` | {{domxref("GLint")}} | | +| `gl.MAX_VERTEX_UNIFORM_BLOCKS` | {{domxref("GLint")}} | | +| `gl.MAX_VERTEX_UNIFORM_COMPONENTS` | {{domxref("GLint")}} | | +| `gl.MIN_PROGRAM_TEXEL_OFFSET` | {{domxref("GLint")}} | | +| `gl.PACK_ROW_LENGTH` | {{domxref("GLint")}} | | +| `gl.PACK_SKIP_PIXELS` | {{domxref("GLint")}} | | +| `gl.PACK_SKIP_ROWS` | {{domxref("GLint")}} | | +| `gl.PIXEL_PACK_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | +| `gl.PIXEL_UNPACK_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | +| `gl.RASTERIZER_DISCARD` | {{domxref("GLboolean")}} | | +| `gl.READ_BUFFER` | {{domxref("GLenum")}} | | +| `gl.READ_FRAMEBUFFER_BINDING` | {{domxref("WebGLFramebuffer")}} | | +| `gl.SAMPLE_ALPHA_TO_COVERAGE` | {{domxref("GLboolean")}} | | +| `gl.SAMPLE_COVERAGE` | {{domxref("GLboolean")}} | | +| `gl.SAMPLER_BINDING` | {{domxref("WebGLSampler")}} | | +| `gl.TEXTURE_BINDING_2D_ARRAY` | {{domxref("WebGLTexture")}} | | +| `gl.TEXTURE_BINDING_3D` | {{domxref("WebGLTexture")}} | | +| `gl.TRANSFORM_FEEDBACK_ACTIVE` | {{domxref("GLboolean")}} | | | `gl.TRANSFORM_FEEDBACK_BINDING` | {{domxref("WebGLTransformFeedback")}} | | -| `gl.TRANSFORM_FEEDBACK_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | -| `gl.TRANSFORM_FEEDBACK_PAUSED` | {{domxref("GLboolean")}} | | -| `gl.UNIFORM_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | -| `gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT` | {{domxref("GLint")}} | | -| `gl.UNPACK_IMAGE_HEIGHT` | {{domxref("GLint")}} | | -| `gl.UNPACK_ROW_LENGTH` | {{domxref("GLint")}} | | -| `gl.UNPACK_SKIP_IMAGES` | {{domxref("GLint")}} | | -| `gl.UNPACK_SKIP_PIXELS` | {{domxref("GLint")}} | | -| `gl.UNPACK_SKIP_ROWS` | {{domxref("GLint")}} | | +| `gl.TRANSFORM_FEEDBACK_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | +| `gl.TRANSFORM_FEEDBACK_PAUSED` | {{domxref("GLboolean")}} | | +| `gl.UNIFORM_BUFFER_BINDING` | {{domxref("WebGLBuffer")}} | | +| `gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT` | {{domxref("GLint")}} | | +| `gl.UNPACK_IMAGE_HEIGHT` | {{domxref("GLint")}} | | +| `gl.UNPACK_ROW_LENGTH` | {{domxref("GLint")}} | | +| `gl.UNPACK_SKIP_IMAGES` | {{domxref("GLint")}} | | +| `gl.UNPACK_SKIP_PIXELS` | {{domxref("GLint")}} | | +| `gl.UNPACK_SKIP_ROWS` | {{domxref("GLint")}} | | | `gl.VERTEX_ARRAY_BINDING` | {{domxref("WebGLVertexArrayObject")}} | | ### WebGL 扩展 当使用 [WebGL 扩展](/zh-CN/docs/Web/API/WebGL_API/Using_Extensions) 时,您可以查询以下 `pname` 参数: -| 常量 | 返回类型 | 扩展 | 描述 | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | -| `ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT` | {{domxref("GLfloat")}} | {{domxref("EXT_texture_filter_anisotropic")}} | 最大可用各向异性。 | -| `ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES` | {{domxref("GLenum")}} | {{domxref("OES_standard_derivatives")}} | GLSL 内置函数的导数计算精度:`dFdx`、 `dFdy` 和 `fwidth`。 | -| `ext.MAX_COLOR_ATTACHMENTS_WEBGL` | {{domxref("GLint")}} | {{domxref("WEBGL_draw_buffers")}} | 帧缓冲区颜色附着点的最大数量。 | -| `ext.MAX_DRAW_BUFFERS_WEBGL` | {{domxref("GLint")}} | {{domxref("WEBGL_draw_buffers")}} | 绘图缓冲区的最大数量。 | -| `ext.DRAW_BUFFER0_WEBGL ext.DRAW_BUFFER1_WEBGL ext.DRAW_BUFFER2_WEBGL ext.DRAW_BUFFER3_WEBGL ext.DRAW_BUFFER4_WEBGL ext.DRAW_BUFFER5_WEBGL ext.DRAW_BUFFER6_WEBGL ext.DRAW_BUFFER7_WEBGL ext.DRAW_BUFFER8_WEBGL ext.DRAW_BUFFER9_WEBGL ext.DRAW_BUFFER10_WEBGL ext.DRAW_BUFFER11_WEBGL ext.DRAW_BUFFER12_WEBGL ext.DRAW_BUFFER13_WEBGL ext.DRAW_BUFFER14_WEBGL ext.DRAW_BUFFER15_WEBGL` | {{domxref("GLenum")}} | {{domxref("WEBGL_draw_buffers")}} | 绘图缓冲区。 | -| `ext.VERTEX_ARRAY_BINDING_OES` | {{domxref("WebGLVertexArrayObjectOES")}} | {{domxref("OES_vertex_array_object")}} | 绑定的顶点数组对象(VAO)。 | -| `ext.TIMESTAMP_EXT` | {{domxref("GLuint64EXT")}} | {{domxref("EXT_disjoint_timer_query")}} | 当前时间。 | -| `ext.GPU_DISJOINT_EXT` | {{domxref("GLboolean")}} | {{domxref("EXT_disjoint_timer_query")}} | 返回 GPU 是否执行了任何不相交的操作。 | +| 常量 | 返回类型 | 扩展 | 描述 | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | --------------------------------------------- | ---------------------------------------------------------- | +| `ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT` | {{domxref("GLfloat")}} | {{domxref("EXT_texture_filter_anisotropic")}} | 最大可用各向异性。 | +| `ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES` | {{domxref("GLenum")}} | {{domxref("OES_standard_derivatives")}} | GLSL 内置函数的导数计算精度:`dFdx`、 `dFdy` 和 `fwidth`。 | +| `ext.MAX_COLOR_ATTACHMENTS_WEBGL` | {{domxref("GLint")}} | {{domxref("WEBGL_draw_buffers")}} | 帧缓冲区颜色附着点的最大数量。 | +| `ext.MAX_DRAW_BUFFERS_WEBGL` | {{domxref("GLint")}} | {{domxref("WEBGL_draw_buffers")}} | 绘图缓冲区的最大数量。 | +| `ext.DRAW_BUFFER0_WEBGL ext.DRAW_BUFFER1_WEBGL ext.DRAW_BUFFER2_WEBGL ext.DRAW_BUFFER3_WEBGL ext.DRAW_BUFFER4_WEBGL ext.DRAW_BUFFER5_WEBGL ext.DRAW_BUFFER6_WEBGL ext.DRAW_BUFFER7_WEBGL ext.DRAW_BUFFER8_WEBGL ext.DRAW_BUFFER9_WEBGL ext.DRAW_BUFFER10_WEBGL ext.DRAW_BUFFER11_WEBGL ext.DRAW_BUFFER12_WEBGL ext.DRAW_BUFFER13_WEBGL ext.DRAW_BUFFER14_WEBGL ext.DRAW_BUFFER15_WEBGL` | {{domxref("GLenum")}} | {{domxref("WEBGL_draw_buffers")}} | 绘图缓冲区。 | +| `ext.VERTEX_ARRAY_BINDING_OES` | {{domxref("WebGLVertexArrayObjectOES")}} | {{domxref("OES_vertex_array_object")}} | 绑定的顶点数组对象(VAO)。 | +| `ext.TIMESTAMP_EXT` | {{domxref("GLuint64EXT")}} | {{domxref("EXT_disjoint_timer_query")}} | 当前时间。 | +| `ext.GPU_DISJOINT_EXT` | {{domxref("GLboolean")}} | {{domxref("EXT_disjoint_timer_query")}} | 返回 GPU 是否执行了任何不相交的操作。 | ## 示例 diff --git a/files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.md b/files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.md index db5a769ea7fa68..87eb1db9642664 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/getprograminfolog/index.md @@ -27,8 +27,8 @@ gl.getProgramInfoLog(program); ### Checking program errors ```js -var canvas = document.getElementsById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementsById("canvas"); +var gl = canvas.getContext("webgl"); var program = gl.createProgram(); //vsSource is the source-code-string of vertex-shader diff --git a/files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.md b/files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.md index c90854dd1e2417..3d3612d1ba8efc 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/getsupportedextensions/index.md @@ -10,7 +10,7 @@ slug: Web/API/WebGLRenderingContext/getSupportedExtensions ## 语法 ```js -getSupportedExtensions() +getSupportedExtensions(); ``` ### 参数 @@ -24,8 +24,8 @@ getSupportedExtensions() ## 示例 ```js -const canvas = document.getElementById('canvas'); -gl = canvas.getContext('webgl'); +const canvas = document.getElementById("canvas"); +gl = canvas.getContext("webgl"); const extensions = gl.getSupportedExtensions(); // Array [ 'ANGLE_instanced_arrays', 'EXT_blend_minmax', … ] diff --git a/files/zh-cn/web/api/webglrenderingcontext/getuniform/index.md b/files/zh-cn/web/api/webglrenderingcontext/getuniform/index.md index 24420f14633091..49b263b7ed57f2 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/getuniform/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/getuniform/index.md @@ -163,7 +163,7 @@ any gl.getUniform(program, location); ## 示例 ```js -var loc = gl.getUniformLocation(program, 'u_foobar'); +var loc = gl.getUniformLocation(program, "u_foobar"); gl.getUniform(program, loc); //code in vertex-shader diff --git a/files/zh-cn/web/api/webglrenderingcontext/index.md b/files/zh-cn/web/api/webglrenderingcontext/index.md index 0efb5e843b89bb..cdd8f118a330b9 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/index.md @@ -10,8 +10,8 @@ slug: Web/API/WebGLRenderingContext 要获得这个接口的对象以用于 2D 和 3D 的图形渲染,可以通过在 `` 元素上调用 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} 函数,调用时传入“webgl”参数: ```js -const canvas = document.getElementById('myCanvas'); -const gl = canvas.getContext('webgl'); +const canvas = document.getElementById("myCanvas"); +const gl = canvas.getContext("webgl"); ``` 当你获取到 canvas 元素的 WebGL 绘图上下文,你便可以在里面绘图。点击 [WebGL 教程](/zh-CN/docs/Web/API/WebGL_API/Tutorial)获取更多资料,例如,关于如何开始 WebGL 编程的知识。 diff --git a/files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.md b/files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.md index 7a2306767ab07a..2b418adfd7a501 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/iscontextlost/index.md @@ -26,7 +26,7 @@ gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS) && !gl.isContextLost()) { var info = gl.getProgramInfoLog(program); - console.log('Error linking program:\n' + info); + console.log("Error linking program:\n" + info); } ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/isenabled/index.md b/files/zh-cn/web/api/webglrenderingcontext/isenabled/index.md index 0cdfbb4cc68fbc..408822d0b5e502 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/isenabled/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/isenabled/index.md @@ -21,17 +21,17 @@ void gl.isEnabled(cap); - : {{domxref("GLenum")}} 指定待检测的 WebGL 功能项。可能的值有: - | Constant | Description | - | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | - | `gl.BLEND` | Blending of the computed fragment color values. See {{domxref("WebGLRenderingContext.blendFunc()")}}. | - | `gl.CULL_FACE` | Culling of polygons. See {{domxref("WebGLRenderingContext.cullFace()")}}. | - | `gl.DEPTH_TEST` | Depth comparisons and updates to the depth buffer. See {{domxref("WebGLRenderingContext.depthFunc()")}}. | - | `gl.DITHER` | Dithering of color components before they get written to the color buffer. | - | `gl.POLYGON_OFFSET_FILL` | Adding an offset to depth values of polygon's fragments. See {{domxref("WebGLRenderingContext.polygonOffset()")}}. | - | `gl.SAMPLE_ALPHA_TO_COVERAGE` | Computation of a temporary coverage value determined by the alpha value. | - | `gl.SAMPLE_COVERAGE` | ANDing the fragment's coverage with the temporary coverage value. See {{domxref("WebGLRenderingContext.sampleCoverage()")}}. | + | Constant | Description | + | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | + | `gl.BLEND` | Blending of the computed fragment color values. See {{domxref("WebGLRenderingContext.blendFunc()")}}. | + | `gl.CULL_FACE` | Culling of polygons. See {{domxref("WebGLRenderingContext.cullFace()")}}. | + | `gl.DEPTH_TEST` | Depth comparisons and updates to the depth buffer. See {{domxref("WebGLRenderingContext.depthFunc()")}}. | + | `gl.DITHER` | Dithering of color components before they get written to the color buffer. | + | `gl.POLYGON_OFFSET_FILL` | Adding an offset to depth values of polygon's fragments. See {{domxref("WebGLRenderingContext.polygonOffset()")}}. | + | `gl.SAMPLE_ALPHA_TO_COVERAGE` | Computation of a temporary coverage value determined by the alpha value. | + | `gl.SAMPLE_COVERAGE` | ANDing the fragment's coverage with the temporary coverage value. See {{domxref("WebGLRenderingContext.sampleCoverage()")}}. | | `gl.SCISSOR_TEST` | Scissor test that discards fragments that are outside of the scissor rectangle. See {{domxref("WebGLRenderingContext.scissor()")}}. | - | `gl.STENCIL_TEST` | Stencil testing and updates to the stencil buffer. See {{domxref("WebGLRenderingContext.stencilFunc()")}}. | + | `gl.STENCIL_TEST` | Stencil testing and updates to the stencil buffer. See {{domxref("WebGLRenderingContext.stencilFunc()")}}. | 当使用 {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}} 的时候,下列附加的值也是可选用的。 diff --git a/files/zh-cn/web/api/webglrenderingcontext/isprogram/index.md b/files/zh-cn/web/api/webglrenderingcontext/isprogram/index.md index 3a11dfe02403fb..8b2b2e078927b6 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/isprogram/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/isprogram/index.md @@ -27,8 +27,8 @@ GLboolean gl.isProgram(program); ### 检查一个 program 是否有效 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var program = gl.createProgram(); // ... diff --git a/files/zh-cn/web/api/webglrenderingcontext/isshader/index.md b/files/zh-cn/web/api/webglrenderingcontext/isshader/index.md index f8cff3fb245358..69b31bfcae7cea 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/isshader/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/isshader/index.md @@ -27,8 +27,8 @@ GLboolean gl.isShader(shader); ### 校验一个 Shader ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var shader = gl.createShader(gl.VERTEX_SHADER); // ... diff --git a/files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.md b/files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.md index 9f78f629bc01b7..269ee353bdebf1 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/linkprogram/index.md @@ -32,9 +32,9 @@ gl.attachShader(program, fragmentShader); gl.linkProgram(program); -if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) { +if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var info = gl.getProgramInfoLog(program); - throw new Error('Could not compile WebGL program. \n\n' + info); + throw new Error("Could not compile WebGL program. \n\n" + info); } ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.md b/files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.md index 6e05daff0f5ecc..7aa5b4537490d5 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/pixelstorei/index.md @@ -26,18 +26,18 @@ None. ## 像素存储参数 -| 模式名称 (`pname`) | 描述 | 类型 | 默认值 | param 的可选值 | Specified in | -| --------------------------------------- | ------------------------------------------------------------ | -------------------------------- | -------------------------- | ------------------------------------- | ------------- | +| 模式名称 (`pname`) | 描述 | 类型 | 默认值 | param 的可选值 | Specified in | +| --------------------------------------- | ------------------------------------------------------------ | ------------------------ | -------------------------- | ------------------------------------- | ------------- | | `gl.PACK_ALIGNMENT` | Packing of pixel data into memory | {{domxref("GLint")}} | 4 | 1, 2, 4, 8 | OpenGL ES 2.0 | | `gl.UNPACK_ALIGNMENT` | Unpacking of pixel data from memory. | {{domxref("GLint")}} | 4 | 1, 2, 4, 8 | OpenGL ES 2.0 | | `gl.UNPACK_FLIP_Y_WEBGL` | 如果为 true,则把图片上下对称翻转坐标轴 (图片本身不变)。 | {{domxref("GLboolean")}} | false | true, false | WebGL | | `gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL` | Multiplies the alpha channel into the other color channels | {{domxref("GLboolean")}} | false | true, false | WebGL | -| `gl.UNPACK_COLORSPACE_CONVERSION_WEBGL` | Default color space conversion or no color space conversion. | {{domxref("GLenum")}} | `gl.BROWSER_DEFAULT_WEBGL` | `gl.BROWSER_DEFAULT_WEBGL`, `gl.NONE` | WebGL | +| `gl.UNPACK_COLORSPACE_CONVERSION_WEBGL` | Default color space conversion or no color space conversion. | {{domxref("GLenum")}} | `gl.BROWSER_DEFAULT_WEBGL` | `gl.BROWSER_DEFAULT_WEBGL`, `gl.NONE` | WebGL | When using a {{domxref("WebGL2RenderingContext", "WebGL 2 context", "", 1)}}, the following values are available additionally: -| Constant | Description | Type | Default value | Allowed values (for `param`) | Specified in | -| ------------------------ | --------------------------------------------------------------------------------------- | ---------------------------- | ------------- | ---------------------------- | ------------- | +| Constant | Description | Type | Default value | Allowed values (for `param`) | Specified in | +| ------------------------ | --------------------------------------------------------------------------------------- | -------------------- | ------------- | ---------------------------- | ------------- | | `gl.PACK_ROW_LENGTH` | Number of pixels in a row. | {{domxref("GLint")}} | 0 | 0 to `Infinity` | OpenGL ES 3.0 | | `gl.PACK_SKIP_PIXELS` | Number of pixel locations skipped before the first pixel is written into memory. | {{domxref("GLint")}} | 0 | 0 to `Infinity` | OpenGL ES 3.0 | | `gl.PACK_SKIP_ROWS` | Number of rows of pixel locations skipped before the first pixel is written into memory | {{domxref("GLint")}} | 0 | 0 to `Infinity` | OpenGL ES 3.0 | diff --git a/files/zh-cn/web/api/webglrenderingcontext/polygonoffset/index.md b/files/zh-cn/web/api/webglrenderingcontext/polygonoffset/index.md index 83c23167c1a438..9976ce5b143a49 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/polygonoffset/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/polygonoffset/index.md @@ -39,7 +39,7 @@ gl.polygonOffset(2, 3); ```js gl.getParameter(gl.POLYGON_OFFSET_FACTOR); // 2 -gl.getParameter(gl.POLYGON_OFFSET_UNITS); // 3 +gl.getParameter(gl.POLYGON_OFFSET_UNITS); // 3 ``` ## 规范 diff --git a/files/zh-cn/web/api/webglrenderingcontext/readpixels/index.md b/files/zh-cn/web/api/webglrenderingcontext/readpixels/index.md index c846a7491c9d7f..48e91ef2d20b9b 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/readpixels/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/readpixels/index.md @@ -100,10 +100,20 @@ readPixels(x, y, width, height, format, type, pixels, dstOffset) ## 示例 ```js -const canvas = document.getElementById('canvas'); -const gl = canvas.getContext('webgl'); -const pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); -gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels); +const canvas = document.getElementById("canvas"); +const gl = canvas.getContext("webgl"); +const pixels = new Uint8Array( + gl.drawingBufferWidth * gl.drawingBufferHeight * 4, +); +gl.readPixels( + 0, + 0, + gl.drawingBufferWidth, + gl.drawingBufferHeight, + gl.RGBA, + gl.UNSIGNED_BYTE, + pixels, +); console.log(pixels); // Uint8Array ``` diff --git a/files/zh-cn/web/api/webglrenderingcontext/texparameter/index.md b/files/zh-cn/web/api/webglrenderingcontext/texparameter/index.md index c14735d0f789d1..807bb8f1955eb7 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/texparameter/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/texparameter/index.md @@ -144,7 +144,11 @@ void gl.texParameteri(GLenum target, GLenum pname, GLint param); ```js gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); -gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST); +gl.texParameteri( + gl.TEXTURE_2D, + gl.TEXTURE_MIN_FILTER, + gl.LINEAR_MIPMAP_NEAREST, +); ``` ## 规范 diff --git a/files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.md b/files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.md index a56eb0a021d0f3..d6f520dfe1b501 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/uniformmatrix/index.md @@ -33,7 +33,7 @@ WebGLRenderingContext.uniformMatrix4fv(location, transpose, value); ## 示例 ```js -gl.uniformMatrix2fv(loc, false, [2,1, 2,2]); +gl.uniformMatrix2fv(loc, false, [2, 1, 2, 2]); ``` ## 规范 diff --git a/files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.md b/files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.md index e47598e8094916..40f0720148c4da 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/validateprogram/index.md @@ -34,9 +34,9 @@ gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.validateProgram(program); -if ( !gl.getProgramParameter( program, gl.LINK_STATUS) ) { +if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var info = gl.getProgramInfoLog(program); - throw '不能编译 WebGL 程序。\n\n' + info; + throw "不能编译 WebGL 程序。\n\n" + info; } gl.useProgram(program); diff --git a/files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.md b/files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.md index 8c0dd9bac1d46c..2adab0c900c621 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/vertexattrib/index.md @@ -37,7 +37,7 @@ void gl.vertexAttrib4fv(index, value); ## 示例 ```js -const a_foobar = gl.getAttribLocation(shaderProgram, 'foobar'); +const a_foobar = gl.getAttribLocation(shaderProgram, "foobar"); //either set each component individually: gl.vertexAttrib3f(a_foobar, 10.0, 5.0, 2.0); //or provide a Float32Array: diff --git a/files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.md b/files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.md index a886dc0693a251..da10485b3c43f0 100644 --- a/files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.md +++ b/files/zh-cn/web/api/webglrenderingcontext/vertexattribpointer/index.md @@ -139,7 +139,7 @@ First, we dynamically create the array buffer from JSON data using a {{domxref(" ```js //load geometry with fetch() and Response.json() -const response = await fetch('assets/geometry.json'); +const response = await fetch("assets/geometry.json"); const vertices = await response.json(); //Create array buffer @@ -150,19 +150,19 @@ for (let i = 0; i < vertices.length; i++) { dv.setFloat32(20 * i, vertices[i].position[0], true); dv.setFloat32(20 * i + 4, vertices[i].position[1], true); dv.setFloat32(20 * i + 8, vertices[i].position[2], true); - dv.setInt8(20 * i + 12, vertices[i].normal[0] * 0x7F); - dv.setInt8(20 * i + 13, vertices[i].normal[1] * 0x7F); - dv.setInt8(20 * i + 14, vertices[i].normal[2] * 0x7F); + dv.setInt8(20 * i + 12, vertices[i].normal[0] * 0x7f); + dv.setInt8(20 * i + 13, vertices[i].normal[1] * 0x7f); + dv.setInt8(20 * i + 14, vertices[i].normal[2] * 0x7f); dv.setInt8(20 * i + 15, 0); - dv.setUint16(20 * i + 16, vertices[i].texCoord[0] * 0xFFFF, true); - dv.setUint16(20 * i + 18, vertices[i].texCoord[1] * 0xFFFF, true); + dv.setUint16(20 * i + 16, vertices[i].texCoord[0] * 0xffff, true); + dv.setUint16(20 * i + 18, vertices[i].texCoord[1] * 0xffff, true); } ``` For higher performance, we could also do the previous JSON to ArrayBuffer conversion on the server-side, e.g. with Node.js. Then we could load the binary file and interpret it as an array buffer: ```js -const response = await fetch('assets/geometry.bin'); +const response = await fetch("assets/geometry.bin"); const buffer = await response.arrayBuffer(); ``` @@ -192,9 +192,9 @@ gl.vertexAttribPointer(2, 2, gl.UNSIGNED_SHORT, true, 20, 16); gl.enableVertexAttribArray(2); //Set the attributes in the vertex shader to the same indices -gl.bindAttribLocation(shaderProgram, 0, 'position'); -gl.bindAttribLocation(shaderProgram, 1, 'normal'); -gl.bindAttribLocation(shaderProgram, 2, 'texUV'); +gl.bindAttribLocation(shaderProgram, 0, "position"); +gl.bindAttribLocation(shaderProgram, 1, "normal"); +gl.bindAttribLocation(shaderProgram, 2, "texUV"); //Since the attribute indices have changed, we must re-link the shader //Note that this will reset all uniforms that were previously set. gl.linkProgram(shaderProgram); @@ -203,15 +203,15 @@ gl.linkProgram(shaderProgram); Or we can use the index provided by the graphics card instead of setting the index ourselves; this avoids the re-linking of the shader program. ```js -const locPosition = gl.getAttribLocation(shaderProgram, 'position'); +const locPosition = gl.getAttribLocation(shaderProgram, "position"); gl.vertexAttribPointer(locPosition, 3, gl.FLOAT, false, 20, 0); gl.enableVertexAttribArray(locPosition); -const locNormal = gl.getAttribLocation(shaderProgram, 'normal'); +const locNormal = gl.getAttribLocation(shaderProgram, "normal"); gl.vertexAttribPointer(locNormal, 4, gl.BYTE, true, 20, 12); gl.enableVertexAttribArray(locNormal); -const locTexUV = gl.getAttribLocation(shaderProgram, 'texUV'); +const locTexUV = gl.getAttribLocation(shaderProgram, "texUV"); gl.vertexAttribPointer(locTexUV, 2, gl.UNSIGNED_SHORT, true, 20, 16); gl.enableVertexAttribArray(locTexUV); ``` diff --git a/files/zh-cn/web/api/webglshader/index.md b/files/zh-cn/web/api/webglshader/index.md index 4fc60ac4a91302..a5d9332fc76b4e 100644 --- a/files/zh-cn/web/api/webglshader/index.md +++ b/files/zh-cn/web/api/webglshader/index.md @@ -12,14 +12,14 @@ slug: Web/API/WebGLShader 要创建一个 **WebGLShader** 需要使用 {{domxref("WebGLRenderingContext.createShader")}},通过 {{domxref("WebGLRenderingContext.shaderSource()")}} 然后挂接 GLSL 源代码 , 最后调用 {{domxref("WebGLRenderingContext.compileShader()")}} 完成着色器(shader)的编译。此时 **WebGLShader** 仍不是可用的形式,他需要被添加到一个 {{domxref("WebGLProgram")}}里。 ```js -function createShader (gl, sourceCode, type) { +function createShader(gl, sourceCode, type) { // Compiles either a shader of type gl.VERTEX_SHADER or gl.FRAGMENT_SHADER - var shader = gl.createShader( type ); - gl.shaderSource( shader, sourceCode ); - gl.compileShader( shader ); + var shader = gl.createShader(type); + gl.shaderSource(shader, sourceCode); + gl.compileShader(shader); - if ( !gl.getShaderParameter(shader, gl.COMPILE_STATUS) ) { - var info = gl.getShaderInfoLog( shader ); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + var info = gl.getShaderInfoLog(shader); throw "Could not compile WebGL program. \n\n" + info; } return shader; @@ -36,25 +36,23 @@ function createShader (gl, sourceCode, type) { ```js var vertexShaderSource = - "attribute vec4 position;\n"+ - "void main() {\n"+ - " gl_Position = position;\n"+ + "attribute vec4 position;\n" + + "void main() {\n" + + " gl_Position = position;\n" + "}\n"; //从上面例子使用 createShader 函数。 -var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER) +var vertexShader = createShader(gl, vertexShaderSource, gl.VERTEX_SHADER); ``` ### 创建一个片元着色器(fragment shader) ```js var fragmentShaderSource = - "void main() {\n"+ - " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"+ - "}\n"; + "void main() {\n" + " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n" + "}\n"; //从上面例子使用 createShader 函数。 -var fragmentShader = createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER) +var fragmentShader = createShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER); ``` ## 规范 diff --git a/files/zh-cn/web/api/webglshaderprecisionformat/index.md b/files/zh-cn/web/api/webglshaderprecisionformat/index.md index 6492deafa35bbf..104fa2bac79e9c 100644 --- a/files/zh-cn/web/api/webglshaderprecisionformat/index.md +++ b/files/zh-cn/web/api/webglshaderprecisionformat/index.md @@ -19,8 +19,8 @@ slug: Web/API/WebGLShaderPrecisionFormat `WebGLShaderPrecisionFormat` 对象通过{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}} 方法来返回。 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 } ``` diff --git a/files/zh-cn/web/api/webgltexture/index.md b/files/zh-cn/web/api/webgltexture/index.md index 0ef4f370ae47f4..8dd48b535718cc 100644 --- a/files/zh-cn/web/api/webgltexture/index.md +++ b/files/zh-cn/web/api/webgltexture/index.md @@ -19,8 +19,8 @@ slug: Web/API/WebGLTexture ### 创建一个纹理 ```js -var canvas = document.getElementById('canvas'); -var gl = canvas.getContext('webgl'); +var canvas = document.getElementById("canvas"); +var gl = canvas.getContext("webgl"); var texture = gl.createTexture(); ``` diff --git a/files/zh-cn/web/api/webgpu_api/index.md b/files/zh-cn/web/api/webgpu_api/index.md index 7bfbb01f22d0ae..14efd16c69f3f2 100644 --- a/files/zh-cn/web/api/webgpu_api/index.md +++ b/files/zh-cn/web/api/webgpu_api/index.md @@ -439,7 +439,7 @@ commandEncoder.copyBufferToBuffer( 0, // 来源缓冲区偏移量 stagingBuffer, 0, // 目的缓冲区偏移量 - BUFFER_SIZE + BUFFER_SIZE, ); // 通过将命令缓冲区数组传递给命令队列以执行来结束 @@ -453,7 +453,7 @@ device.queue.submit([commandEncoder.finish()]); await stagingBuffer.mapAsync( GPUMapMode.READ, 0, // 偏移量 - BUFFER_SIZE // 长度 + BUFFER_SIZE, // 长度 ); const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER_SIZE); diff --git a/files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.md b/files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.md index 3b95c6e82c1fd6..5086b1eca1c066 100644 --- a/files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.md +++ b/files/zh-cn/web/api/webrtc_api/signaling_and_video_calling/index.md @@ -36,7 +36,7 @@ function sendToOneUser(target, msgString) { var isUnique = true; var i; - for (i=0; i -
- - - -
- +
+
+ + + +
+
``` 此处定义的页面结构使用了 {{HTMLElement("div")}} 元素,通过启用 CSS,我们可以完全控制页面布局。我们将跳过本指南中的布局细节,但你可以[看看 GitHub 上的 CSS](https://github.com/mdn/samples-server/tree/master/s/webrtc-from-chat/chat.css),了解如何处理它。注意这两个 {{HTMLElement("video")}} 元素,一个用于观看自己,一个用于连接,还有 {{HTMLElement("button")}} 元素。 @@ -231,7 +229,7 @@ function handleUserlistMsg(msg) { ```js var mediaConstraints = { audio: true, // We want an audio track - video: true // ...and we want a video track + video: true, // ...and we want a video track }; function invite(evt) { @@ -241,7 +239,9 @@ function invite(evt) { var clickedUsername = evt.target.textContent; if (clickedUsername === myUsername) { - alert("I'm afraid I can't let you talk to yourself. That would be weird."); + alert( + "I'm afraid I can't let you talk to yourself. That would be weird.", + ); return; } @@ -249,12 +249,13 @@ function invite(evt) { createPeerConnection(); - navigator.mediaDevices.getUserMedia(mediaConstraints) - .then(function(localStream) { - document.getElementById("local_video").srcObject = localStream; - myPeerConnection.addStream(localStream); - }) - .catch(handleGetUserMediaError); + navigator.mediaDevices + .getUserMedia(mediaConstraints) + .then(function (localStream) { + document.getElementById("local_video").srcObject = localStream; + myPeerConnection.addStream(localStream); + }) + .catch(handleGetUserMediaError); } } ``` @@ -281,10 +282,12 @@ function invite(evt) { ```js function handleGetUserMediaError(e) { - switch(e.name) { + switch (e.name) { case "NotFoundError": - alert("Unable to open your call because no camera and/or microphone" + - "were found."); + alert( + "Unable to open your call because no camera and/or microphone" + + "were found.", + ); break; case "SecurityError": case "PermissionDeniedError": @@ -358,18 +361,20 @@ function createPeerConnection() { ```js function handleNegotiationNeededEvent() { - myPeerConnection.createOffer().then(function(offer) { - return myPeerConnection.setLocalDescription(offer); - }) - .then(function() { - sendToServer({ - name: myUsername, - target: targetUsername, - type: "video-offer", - sdp: myPeerConnection.localDescription - }); - }) - .catch(reportError); + myPeerConnection + .createOffer() + .then(function (offer) { + return myPeerConnection.setLocalDescription(offer); + }) + .then(function () { + sendToServer({ + name: myUsername, + target: targetUsername, + type: "video-offer", + sdp: myPeerConnection.localDescription, + }); + }) + .catch(reportError); } ``` @@ -462,7 +467,7 @@ function handleICECandidateEvent(event) { sendToServer({ type: "new-ice-candidate", target: targetUsername, - candidate: event.candidate + candidate: event.candidate, }); } } @@ -489,8 +494,7 @@ function handleICECandidateEvent(event) { function handleNewICECandidateMsg(msg) { var candidate = new RTCIceCandidate(msg.candidate); - myPeerConnection.addIceCandidate(candidate) - .catch(reportError); + myPeerConnection.addIceCandidate(candidate).catch(reportError); } ``` @@ -552,7 +556,7 @@ function hangUpCall() { sendToServer({ name: myUsername, target: targetUsername, - type: "hang-up" + type: "hang-up", }); } ``` @@ -579,11 +583,11 @@ function closeVideoCall() { myPeerConnection.onnegotiationneeded = null; if (remoteVideo.srcObject) { - remoteVideo.srcObject.getTracks().forEach(track => track.stop()); + remoteVideo.srcObject.getTracks().forEach((track) => track.stop()); } if (localVideo.srcObject) { - localVideo.srcObject.getTracks().forEach(track => track.stop()); + localVideo.srcObject.getTracks().forEach((track) => track.stop()); } myPeerConnection.close(); @@ -621,7 +625,7 @@ function closeVideoCall() { ```js function handleICEConnectionStateChangeEvent(event) { - switch(myPeerConnection.iceConnectionState) { + switch (myPeerConnection.iceConnectionState) { case "closed": case "failed": case "disconnected": @@ -638,13 +642,13 @@ function handleICEConnectionStateChangeEvent(event) { 同样,我们监听 {{domxref("RTCPeerConnection.signalingstatechange_event", "signalingstatechange")}} 事件。如果信号状态变为 `closed`,我们同样关闭呼叫。 ```js - myPeerConnection.onsignalingstatechange = function(event) { - switch(myPeerConnection.signalingState) { - case "closed": - closeVideoCall(); - break; - } - }; +myPeerConnection.onsignalingstatechange = function (event) { + switch (myPeerConnection.signalingState) { + case "closed": + closeVideoCall(); + break; + } +}; ``` > **备注:** `closed`的信令状态已被弃用,取而代之的是 `closed`{{domxref("RTCPeerConnection.iceConnectionState", "iceConnectionState")}}。我们在这里监听它以增加一点向后兼容性。 diff --git a/files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.md b/files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.md index 4378953bdd0fe3..21fbe28c3d062f 100644 --- a/files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.md +++ b/files/zh-cn/web/api/webrtc_api/simple_rtcdatachannel_sample/index.md @@ -17,7 +17,11 @@ slug: Web/API/WebRTC_API/Simple_RTCDataChannel_sample - ``` @@ -25,15 +29,23 @@ slug: Web/API/WebRTC_API/Simple_RTCDataChannel_sample 然后我们还有一个输入框,用来输入消息。一个按钮,来触发发送事件。这个 {{HTMLElement("div")}} 是给 channel 中第一个节点使用的。 ```html -
- - -
+
+ + +
``` 最后,还有一个小 DIV 用来显示收到的内容。这个 {{HTMLElement("div")}} 是给 channel 中第二个 peer 使用的。 @@ -56,17 +68,17 @@ WebRTC API 大量使用了{{jsxref("Promise")}}. 这样会让建立链接的过 ```js function startup() { - connectButton = document.getElementById('connectButton'); - disconnectButton = document.getElementById('disconnectButton'); - sendButton = document.getElementById('sendButton'); - messageInputBox = document.getElementById('message'); - receiveBox = document.getElementById('receivebox'); + connectButton = document.getElementById("connectButton"); + disconnectButton = document.getElementById("disconnectButton"); + sendButton = document.getElementById("sendButton"); + messageInputBox = document.getElementById("message"); + receiveBox = document.getElementById("receivebox"); // Set event listeners for user interface widgets - connectButton.addEventListener('click', connectPeers, false); - disconnectButton.addEventListener('click', disconnectPeers, false); - sendButton.addEventListener('click', sendMessage, false); + connectButton.addEventListener("click", connectPeers, false); + disconnectButton.addEventListener("click", disconnectPeers, false); + sendButton.addEventListener("click", sendMessage, false); } ``` @@ -108,13 +120,13 @@ remoteConnection.ondatachannel = receiveChannelCallback; > **备注:** 在现实场景,当参与连接的两节点运行于不同的上下文,建立连接的过程或稍微复杂些,每一次双方通过调用{{domxref("RTCPeerConnection.addIceCandidate()")}},提出连接方式的建议 (例如:UDP,、中继 UDP、TCP 之类的) ,双方来回往复直到达成一致。本文既然不涉及现实网络环境,因此我们假定双方接受首次连接建议。 ```js - localConnection.onicecandidate = e => !e.candidate - || remoteConnection.addIceCandidate(e.candidate) - .catch(handleAddCandidateError); +localConnection.onicecandidate = (e) => + !e.candidate || + remoteConnection.addIceCandidate(e.candidate).catch(handleAddCandidateError); - remoteConnection.onicecandidate = e => !e.candidate - || localConnection.addIceCandidate(e.candidate) - .catch(handleAddCandidateError); +remoteConnection.onicecandidate = (e) => + !e.candidate || + localConnection.addIceCandidate(e.candidate).catch(handleAddCandidateError); ``` 我们配置每个 {{domxref("RTCPeerConnection")}} 对于事件 {{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}} 建立事件处理。 @@ -124,13 +136,18 @@ remoteConnection.ondatachannel = receiveChannelCallback; 建立节点连接的最后一项是创建一个连接 offer. ```js - localConnection.createOffer() - .then(offer => localConnection.setLocalDescription(offer)) - .then(() => remoteConnection.setRemoteDescription(localConnection.localDescription)) - .then(() => remoteConnection.createAnswer()) - .then(answer => remoteConnection.setLocalDescription(answer)) - .then(() => localConnection.setRemoteDescription(remoteConnection.localDescription)) - .catch(handleCreateDescriptionError); +localConnection + .createOffer() + .then((offer) => localConnection.setLocalDescription(offer)) + .then(() => + remoteConnection.setRemoteDescription(localConnection.localDescription), + ) + .then(() => remoteConnection.createAnswer()) + .then((answer) => remoteConnection.setLocalDescription(answer)) + .then(() => + localConnection.setRemoteDescription(remoteConnection.localDescription), + ) + .catch(handleCreateDescriptionError); ``` 逐行解读上面的代码: @@ -150,13 +167,13 @@ remoteConnection.ondatachannel = receiveChannelCallback; 当 peer-to-peer 连接的任何一方成功连接,相应的 {{domxref("RTCPeerConnection")}} 的 {{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}} 事件将被触发。在事件的处理中可以执行任何需要的操作,但在本例中,我们所需要做的只是更新用户界面。 ```js - function handleLocalAddCandidateSuccess() { - connectButton.disabled = true; - } +function handleLocalAddCandidateSuccess() { + connectButton.disabled = true; +} - function handleRemoteAddCandidateSuccess() { - disconnectButton.disabled = false; - } +function handleRemoteAddCandidateSuccess() { + disconnectButton.disabled = false; +} ``` 当 local 节点连接成功时,禁用 "Connect" 按钮,当 remote 节点连接时许用 "Disconnect" 按钮。 @@ -166,12 +183,12 @@ remoteConnection.ondatachannel = receiveChannelCallback; {{domxref("RTCPeerConnection")}} 一旦 open,事件{{domxref("RTCPeerConnection.datachannel_event", "datachannel")}} 被发送到远端以完成打开数据通道的处理,该事件触发 `receiveChannelCallback()` 方法,如下所示: ```js - function receiveChannelCallback(event) { - receiveChannel = event.channel; - receiveChannel.onmessage = handleReceiveMessage; - receiveChannel.onopen = handleReceiveChannelStatusChange; - receiveChannel.onclose = handleReceiveChannelStatusChange; - } +function receiveChannelCallback(event) { + receiveChannel = event.channel; + receiveChannel.onmessage = handleReceiveMessage; + receiveChannel.onopen = handleReceiveChannelStatusChange; + receiveChannel.onclose = handleReceiveChannelStatusChange; +} ``` 事件 {{domxref("RTCPeerConnection.datachannel_event", "datachannel")}} 在它的 channel 属性中包括了:对代表 remote 节点的 channel 的{{domxref("RTCDataChannel")}} 的指向,它保存了我们用以在该 channel 上对我们希望处理的事件建立的事件监听。一旦侦听建立,每当 remote 节点接收到数据 `handleReceiveMessage()` 方法将被调用,每当通道的连接状态发生改变 `handleReceiveChannelStatusChange()` 方法将被调用,因此通道完全打开或者关闭时我们都可以作出相应的相应。 @@ -183,24 +200,24 @@ local 节点和 remote 节点采用同样的方法处理表示通道连接状态 当 local 节点遭遇 open 或者 close 事件,`handleSendChannelStatusChange()` 方法被调用: ```js - function handleSendChannelStatusChange(event) { - if (sendChannel) { - var state = sendChannel.readyState; - - if (state === "open") { - messageInputBox.disabled = false; - messageInputBox.focus(); - sendButton.disabled = false; - disconnectButton.disabled = false; - connectButton.disabled = true; - } else { - messageInputBox.disabled = true; - sendButton.disabled = true; - connectButton.disabled = false; - disconnectButton.disabled = true; - } +function handleSendChannelStatusChange(event) { + if (sendChannel) { + var state = sendChannel.readyState; + + if (state === "open") { + messageInputBox.disabled = false; + messageInputBox.focus(); + sendButton.disabled = false; + disconnectButton.disabled = false; + connectButton.disabled = true; + } else { + messageInputBox.disabled = true; + sendButton.disabled = true; + connectButton.disabled = false; + disconnectButton.disabled = true; } } +} ``` 如果通道状态已经变更为 "open", 意味着我们已经完成了在两对等节点之间建立连接。相应地用户界面根据状态更新,许用并将输入光标聚焦在 text 输入框,以便用户可以立即输入要发送给对方的文本消息,同时界面许用 "Send" 和 "Disconnect" 按钮(既然它们已经准备好了),禁用"Connect"按钮,既然在已经建立连接的情况下用不着它。 @@ -210,12 +227,13 @@ local 节点和 remote 节点采用同样的方法处理表示通道连接状态 另一方面,作为我们例子的 remote 节点,则无视这些状态改变事件,仅仅是在控制台输出它们: ```js - function handleReceiveChannelStatusChange(event) { - if (receiveChannel) { - console.log("Receive channel's status has changed to " + - receiveChannel.readyState); - } +function handleReceiveChannelStatusChange(event) { + if (receiveChannel) { + console.log( + "Receive channel's status has changed to " + receiveChannel.readyState, + ); } +} ``` `handleReceiveChannelStatusChange()` 方法接收到发生的事件,事件类型为 {{domxref("RTCDataChannelEvent")}}. @@ -225,13 +243,13 @@ local 节点和 remote 节点采用同样的方法处理表示通道连接状态 当用户按下 "Send" 按钮,触发我们已建立的该按钮的 [`click`](/zh-CN/docs/Web/API/Element/click_event) 事件处理逻辑,在处理逻辑中调用 sendMessage() 方法。该方法也足够简单: ```js - function sendMessage() { - var message = messageInputBox.value; - sendChannel.send(message); +function sendMessage() { + var message = messageInputBox.value; + sendChannel.send(message); - messageInputBox.value = ""; - messageInputBox.focus(); - } + messageInputBox.value = ""; + messageInputBox.focus(); +} ``` 首先,待发送的消息文本从文本输入框的 [`value`](/zh-CN/docs/Web/HTML/Element/input#value)属性获得,之后该文本通过调用 {{domxref("RTCDataChannel.send", "sendChannel.send()")}}发送到 remote 节点。都搞定了!余下的只是些用户体验糖 ——清空并聚焦文本输入框,以便用户可以立即开始下一条消息的输入。 @@ -241,13 +259,13 @@ local 节点和 remote 节点采用同样的方法处理表示通道连接状态 当远程通道发生“message”事件时,我们的 handleReceiveMessage() 方法被调用来处理事件。 ```js - function handleReceiveMessage(event) { - var el = document.createElement("p"); - var txtNode = document.createTextNode(event.data); +function handleReceiveMessage(event) { + var el = document.createElement("p"); + var txtNode = document.createTextNode(event.data); - el.appendChild(txtNode); - receiveBox.appendChild(el); - } + el.appendChild(txtNode); + receiveBox.appendChild(el); +} ``` 该方法只是简单地注入了一些 {{Glossary("DOM")}},它创建了 {{HTMLElement("p")}} (paragraph) 元素,然后创建了 {{domxref("Text")}} 用于显示从事件的`data` 属性拿到的消息文本。该 text node 作为子节点附加到`receiveBox` block,显示在浏览器窗口内容区。 @@ -257,32 +275,31 @@ local 节点和 remote 节点采用同样的方法处理表示通道连接状态 当用户点击"Disconnect" 按钮。在之前我们设置的按钮事件处理逻辑中`disconnectPeers()` 方法被调用。 ```js - function disconnectPeers() { - - // Close the RTCDataChannels if they're open. +function disconnectPeers() { + // Close the RTCDataChannels if they're open. - sendChannel.close(); - receiveChannel.close(); + sendChannel.close(); + receiveChannel.close(); - // Close the RTCPeerConnections + // Close the RTCPeerConnections - localConnection.close(); - remoteConnection.close(); + localConnection.close(); + remoteConnection.close(); - sendChannel = null; - receiveChannel = null; - localConnection = null; - remoteConnection = null; + sendChannel = null; + receiveChannel = null; + localConnection = null; + remoteConnection = null; - // Update user interface elements + // Update user interface elements - connectButton.disabled = false; - disconnectButton.disabled = true; - sendButton.disabled = true; + connectButton.disabled = false; + disconnectButton.disabled = true; + sendButton.disabled = true; - messageInputBox.value = ""; - messageInputBox.disabled = true; - } + messageInputBox.value = ""; + messageInputBox.disabled = true; +} ``` 该方法首先关闭每个节点的{{domxref("RTCDataChannel")}},之后类似地关闭每个节点的 {{domxref("RTCPeerConnection")}}。将所有对它们的指向置为`null` 以避免意外的复用。之后更新界面状态以符合目前已经不存在连接的事实。 diff --git a/files/zh-cn/web/api/websocket/error_event/index.md b/files/zh-cn/web/api/websocket/error_event/index.md index f05ec1bcce3f84..59ab4fefce38a3 100644 --- a/files/zh-cn/web/api/websocket/error_event/index.md +++ b/files/zh-cn/web/api/websocket/error_event/index.md @@ -1,5 +1,5 @@ --- -title: 'WebSocket: 错误事件' +title: "WebSocket: 错误事件" slug: Web/API/WebSocket/error_event --- @@ -33,12 +33,12 @@ slug: Web/API/WebSocket/error_event ```js // Create WebSocket connection // 创建一个 WebSocket 连接 -const socket = new WebSocket('ws://localhost:8080'); +const socket = new WebSocket("ws://localhost:8080"); // Listen for possible errors // 监听可能发生的错误 -socket.addEventListener('error', function (event) { - console.log('WebSocket error: ', event); +socket.addEventListener("error", function (event) { + console.log("WebSocket error: ", event); }); ``` diff --git a/files/zh-cn/web/api/websocket/index.md b/files/zh-cn/web/api/websocket/index.md index 1f62e96b31f381..26e47bf4036fe8 100644 --- a/files/zh-cn/web/api/websocket/index.md +++ b/files/zh-cn/web/api/websocket/index.md @@ -74,16 +74,16 @@ slug: Web/API/WebSocket ```js // Create WebSocket connection. -const socket = new WebSocket('ws://localhost:8080'); +const socket = new WebSocket("ws://localhost:8080"); // Connection opened -socket.addEventListener('open', function (event) { - socket.send('Hello Server!'); +socket.addEventListener("open", function (event) { + socket.send("Hello Server!"); }); // Listen for messages -socket.addEventListener('message', function (event) { - console.log('Message from server ', event.data); +socket.addEventListener("message", function (event) { + console.log("Message from server ", event.data); }); ``` diff --git a/files/zh-cn/web/api/websocket/message_event/index.md b/files/zh-cn/web/api/websocket/message_event/index.md index 7101fcd7679e3f..215122c8a9a929 100644 --- a/files/zh-cn/web/api/websocket/message_event/index.md +++ b/files/zh-cn/web/api/websocket/message_event/index.md @@ -1,5 +1,5 @@ --- -title: 'WebSocket: message event' +title: "WebSocket: message event" slug: Web/API/WebSocket/message_event --- @@ -7,21 +7,21 @@ slug: Web/API/WebSocket/message_event `message` 事件会在 `WebSocket` 接收到新消息时被触发。 -| 起泡(Bubbles) | 不 | -| ---------------- | ---------------------------------------------------------------- | -| 可取消 | 不 | -| 接口 | {{domxref("MessageEvent")}} | +| 起泡(Bubbles) | 不 | +| ---------------- | ----------------------------------------------- | +| 可取消 | 不 | +| 接口 | {{domxref("MessageEvent")}} | | 事件处理程序属性 | {{ domxref("WebSocket.onmessage","onmessage")}} | ## 例子 ```js // 创建一个 WebSocket 连接 -const socket = new WebSocket('ws://localhost:8080'); +const socket = new WebSocket("ws://localhost:8080"); // 监听消息 -socket.addEventListener('message', function (event) { - console.log('Message from server ', event.data); +socket.addEventListener("message", function (event) { + console.log("Message from server ", event.data); }); ``` diff --git a/files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.md b/files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.md index e4dfe7ca8caa9a..8e229c589df4bd 100644 --- a/files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.md +++ b/files/zh-cn/web/api/websockets_api/writing_websocket_client_applications/index.md @@ -43,7 +43,10 @@ WebSocket WebSocket( 本例创建了一个新的 WebSocket,连接到地址为 `ws://www.example.com/socketserver` 的服务器。请求中命名了一个自定义的协议 "protocolOne",这一部分可以省略。 ```js -var exampleSocket = new WebSocket("ws://www.example.com/socketserver", "protocolOne"); +var exampleSocket = new WebSocket( + "ws://www.example.com/socketserver", + "protocolOne", +); ``` 返回后,`exampleSocket.readyState` 参数为 `CONNECTING`。一旦连接可以传送数据,`readyState` 就会变成 `OPEN` 。 @@ -51,7 +54,10 @@ var exampleSocket = new WebSocket("ws://www.example.com/socketserver", "protocol 如果你想建立一个支持协议可选的连接,你可以指定协议的列表: ```js -var exampleSocket = new WebSocket("ws://www.example.com/socketserver", ["protocolOne", "protocolTwo"]); +var exampleSocket = new WebSocket("ws://www.example.com/socketserver", [ + "protocolOne", + "protocolTwo", +]); ``` 一旦连接建立了(也就是说 `readyState` 是 `OPEN`) `exampleSocket.protocol` 就会告诉你服务器选择了哪个协议。 @@ -89,8 +95,8 @@ function sendText() { var msg = { type: "message", text: document.getElementById("text").value, - id: clientID, - date: Date.now() + id: clientID, + date: Date.now(), }; // 把 msg 对象作为 JSON 格式字符串发送 @@ -108,7 +114,7 @@ WebSockets 是一个基于事件的 API;收到消息的时候,一个 "messag ```js exampleSocket.onmessage = function (event) { console.log(event.data); -} +}; ``` ### 接受与解析 JSON 对象 diff --git a/files/zh-cn/web/api/webvr_api/concepts/index.md b/files/zh-cn/web/api/webvr_api/concepts/index.md index 2014ca72b2eb51..a9626523c78a17 100644 --- a/files/zh-cn/web/api/webvr_api/concepts/index.md +++ b/files/zh-cn/web/api/webvr_api/concepts/index.md @@ -58,25 +58,25 @@ slug: Web/API/WebVR_API/Concepts 1. 位置——HMD 设备的位置基于一个 3D 坐标空间中的三个轴——X 代表左右移动,Y 代表上下移动,Z 代表朝向和远离位置传感设备。在 WEBVR 中: - - x position is represented by {{domxref("VRPositionState.position")}}.x. - - y position is represented by {{domxref("VRPositionState.position")}}.y. - - z position is represented by {{domxref("VRPositionState.position")}}.z. + - x position is represented by {{domxref("VRPositionState.position")}}.x. + - y position is represented by {{domxref("VRPositionState.position")}}.y. + - z position is represented by {{domxref("VRPositionState.position")}}.z. 2. 方位——HMD 在三维坐标空间中绕三条轴线的旋转。Pitch 为绕 x 轴旋转,yaw 为绕 y 轴旋转,而 roll 则为绕 z 轴旋转。在 WEBVR 中: - - Pitch is represented by {{domxref("VRPositionState.orientation")}}.x. - - Yaw is represented by {{domxref("VRPositionState.orientation")}}.y. - - Roll is represented by {{domxref("VRPositionState.orientation")}}.z. + - Pitch is represented by {{domxref("VRPositionState.orientation")}}.x. + - Yaw is represented by {{domxref("VRPositionState.orientation")}}.y. + - Roll is represented by {{domxref("VRPositionState.orientation")}}.z. 3. 速度——在 VR 中有两种需要被考虑的速度: - - 线速度——HMD 追踪的沿着三种轴向之一的速度。这类的信息可以通过 {{domxref("VRPositionState.linearVelocity")}} 接收(x、y 和 z) - - 角速度——就是 HMD 设备绕着三种轴向之一旋转的速度。这类的信息可以通过 {{domxref("VRPositionState.angularVelocity")}} 接收(x、y 和 z) + - 线速度——HMD 追踪的沿着三种轴向之一的速度。这类的信息可以通过 {{domxref("VRPositionState.linearVelocity")}} 接收(x、y 和 z) + - 角速度——就是 HMD 设备绕着三种轴向之一旋转的速度。这类的信息可以通过 {{domxref("VRPositionState.angularVelocity")}} 接收(x、y 和 z) 4. 加速度——在 VR 中有两种需要被考虑的加速度: - - 线性加速度——HMD 设备沿着轴向追踪的加速度。这类的信息可以通过 {{domxref("VRPositionState.linearAcceleration")}} 接收(x、y 和 z) - - 角度加速度——HMD 设备绕着轴旋转的加速度。这类的信息可以通过 {{domxref("VRPositionState.angularAcceleration")}} 接收(x、y 和 z) + - 线性加速度——HMD 设备沿着轴向追踪的加速度。这类的信息可以通过 {{domxref("VRPositionState.linearAcceleration")}} 接收(x、y 和 z) + - 角度加速度——HMD 设备绕着轴旋转的加速度。这类的信息可以通过 {{domxref("VRPositionState.angularAcceleration")}} 接收(x、y 和 z) ## 视野 diff --git a/files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.md b/files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.md index a8051d2c008730..8c1ec536a1aeb2 100644 --- a/files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.md +++ b/files/zh-cn/web/api/webvr_api/using_the_webvr_api/index.md @@ -66,7 +66,7 @@ However, what you really want is something that grabs a pair of devices (perhaps ```js var gHMD, gPositionSensor; -navigator.getVRDevices().then(function(devices) { +navigator.getVRDevices().then(function (devices) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof HMDVRDevice) { gHMD = devices[i]; @@ -76,7 +76,10 @@ navigator.getVRDevices().then(function(devices) { if (gHMD) { for (var i = 0; i < devices.length; ++i) { - if (devices[i] instanceof PositionSensorVRDevice && devices[i].hardwareUnitId === gHMD.hardwareUnitId) { + if ( + devices[i] instanceof PositionSensorVRDevice && + devices[i].hardwareUnitId === gHMD.hardwareUnitId + ) { gPositionSensor = devices[i]; break; } @@ -94,9 +97,9 @@ The scene is rendered on a {{htmlelement("canvas")}} element, created and placed 场景最终是通过 {{htmlelement("canvas")}} 标记元素来显示。canvas 画布可通过以下 JS 代码来创建。 ```js -var myCanvas = document.createElement('canvas'); -var ctx = myCanvas.getContext('2d'); -var body = document.querySelector('body'); +var myCanvas = document.createElement("canvas"); +var ctx = myCanvas.getContext("2d"); +var body = document.querySelector("body"); body.appendChild(myCanvas); ``` @@ -105,7 +108,7 @@ Next, we create a new [image](/zh-CN/docs/Web/API/HTMLImageElement) and use a [` ```js var image = new Image(); -image.src = 'firefox.png'; +image.src = "firefox.png"; image.onload = draw; ``` @@ -118,8 +121,8 @@ draw() 方法的实现代码参考如下: function draw() { WIDTH = window.innerWidth; HEIGHT = window.innerHeight; - lCtrOffset = WIDTH*0.25; - rCtrOffset = WIDTH*0.25; + lCtrOffset = WIDTH * 0.25; + rCtrOffset = WIDTH * 0.25; myCanvas.width = WIDTH; myCanvas.height = HEIGHT; @@ -162,18 +165,22 @@ function setView() { First we call {{domxref("PositionSensorVRDevice.getState")}} on the reference to our position sensor. This method returns everything you might want to know about the current state of the HMD — accessible through a {{domxref("VRPositionState")}} object — including its position, orientation, and more advanced information such as linear and angular velocity/acceleration. ```js - if(posState.hasPosition) { - posPara.textContent = 'Position: x' + roundToTwo(posState.position.x) + " y" - + roundToTwo(posState.position.y) + " z" - + roundToTwo(posState.position.z); - xPos = -posState.position.x * WIDTH * 2; - yPos = posState.position.y * HEIGHT * 2; - if(-posState.position.z > 0.01) { - zPos = -posState.position.z; - } else { - zPos = 0.01; - } +if (posState.hasPosition) { + posPara.textContent = + "Position: x" + + roundToTwo(posState.position.x) + + " y" + + roundToTwo(posState.position.y) + + " z" + + roundToTwo(posState.position.z); + xPos = -posState.position.x * WIDTH * 2; + yPos = posState.position.y * HEIGHT * 2; + if (-posState.position.z > 0.01) { + zPos = -posState.position.z; + } else { + zPos = 0.01; } +} ``` In the next part, we first check to make sure valid position information is available for the HMD using {{domxref("VRPositionState.hasPosition")}}, so that we don't return an error and stop the app working (if the HMD is switched off, or not pointing at the position sensor.) @@ -183,15 +190,18 @@ Then we output the current position information to a paragraph in the app UI for Last up, we set our `xPos`, `yPos`, and `zPos` variables relative to the position information stored in {{domxref("VRPositionState.position")}}. You'll notice that we have used an `if ... else` block to make sure the `zPos` value stays at 0.01 or above — the app was throwing an error if it went below 0. ```js - if(posState.hasOrientation) { - orientPara.textContent = 'Orientation: x' + roundToTwo(posState.orientation.x) + " y" - + roundToTwo(posState.orientation.y) + " z" - + roundToTwo(posState.orientation.z); - xOrient = posState.orientation.x * WIDTH; - yOrient = -posState.orientation.y * HEIGHT * 2; - zOrient = posState.orientation.z * 180; - - } +if (posState.hasOrientation) { + orientPara.textContent = + "Orientation: x" + + roundToTwo(posState.orientation.x) + + " y" + + roundToTwo(posState.orientation.y) + + " z" + + roundToTwo(posState.orientation.z); + xOrient = posState.orientation.x * WIDTH; + yOrient = -posState.orientation.y * HEIGHT * 2; + zOrient = posState.orientation.z * 180; +} ``` Next, we use a similar process to update the scene according to the HMD's orientation — check that valid orientation data is available using {{domxref("VRPositionState.hasOrientation")}}, display orientation data in the UI for informational purposes, and then set the `xOrient`, `yOrient`, and `zOrient` values relative to the orientation information stored in {{domxref("VRPositionState.orientation")}}. @@ -216,10 +226,10 @@ function drawImages() { First we draw a white {{domxref("CanvasRenderingContext2D.fillRect","fillRect()")}} to clear the scene before the next frame is drawn. ```js - ctx.save(); - ctx.beginPath(); - ctx.translate(WIDTH/4,HEIGHT/2); - ctx.rect(-(WIDTH/4),-(HEIGHT/2),WIDTH/2,HEIGHT); +ctx.save(); +ctx.beginPath(); +ctx.translate(WIDTH / 4, HEIGHT / 2); +ctx.rect(-(WIDTH / 4), -(HEIGHT / 2), WIDTH / 2, HEIGHT); ``` Next, we save the context state with {{domxref("CanvasRenderingContext2D.save","save()")}} so we can treat the left eye view as a separate image and not have its code affect the right eye view. @@ -235,13 +245,19 @@ Note that the `rect()` has to be drawn starting from minus a quarter of the widt Now we {{domxref("CanvasRenderingContext2D.clip","clip()")}} the canvas. Because we called this just after the `rect()` was drawn, anything else that we do on the canvas will be constrained inside the `rect()`, with any overflow hidden until a `restore()` call is made (see later on.) This ensures that the whole left eye view will remain separate from the right eye view. ```js - ctx.rotate(zOrient * Math.PI / 180); +ctx.rotate((zOrient * Math.PI) / 180); ``` A rotation is now applied to the image, related to the current value of `zOrient`, so that the scene rotates as you rotate your head. ```js - ctx.drawImage(image,-(WIDTH/4)+lCtrOffset-((image.width)/(2*(1/zPos)))+xPos-yOrient,-((image.height)/(2*(1/zPos)))+yPos+xOrient,image.width*zPos,image.height*zPos); +ctx.drawImage( + image, + -(WIDTH / 4) + lCtrOffset - image.width / (2 * (1 / zPos)) + xPos - yOrient, + -(image.height / (2 * (1 / zPos))) + yPos + xOrient, + image.width * zPos, + image.height * zPos, +); ``` Now for the actual image drawing! This rather nasty line of code needs breaking down, so here it is, argument by argument: @@ -253,14 +269,14 @@ Now for the actual image drawing! This rather nasty line of code needs breaking - `image.height*zPos`: The height to draw the image; this is modified by `zPos` so it will be drawn bigger as you get closer to it. ```js - ctx.strokeStyle = "black"; - ctx.stroke(); +ctx.strokeStyle = "black"; +ctx.stroke(); ``` Next we draw a black {{domxref("CanvasRenderingContext2D.stroke","stroke()")}} around the left eye view, just to aid the view separation a bit more. ```js - ctx.restore(); +ctx.restore(); ``` Finally, we {{domxref("CanvasRenderingContext2D.restore","restore()")}} the canvas so we can then go on to draw the right eye view. @@ -281,7 +297,7 @@ The VR effect is much more effective if you set your app runnning in [fullscreen In this case I have just kept things simple, running a `fullScreen()` function when the canvas is clicked: ```js -myCanvas.addEventListener('click',fullScreen,false); +myCanvas.addEventListener("click", fullScreen, false); ``` The `fullScreen()` function checks which version of the `requestFullscreen()` method is present on the canvas (this will differ by browser) and then calls the appropriate one, for maximum compatibility: @@ -311,9 +327,9 @@ First of all, you can use the {{domxref("PositionSensorVRDevice.resetSensor")}} ``` ```js -document.querySelector('button').onclick = function() { +document.querySelector("button").onclick = function () { gPositionSensor.resetSensor(); -} +}; ``` The other thing to calibrate is the field of view (FOV) of your headset — how much of the scene can be seen in the up, right, down and left directions. This information can be retrieved for each eye separately using the {{domxref("HMDVRDevice.getEyeParameters")}} method, which returns parameters for each eye separately (you need to call it twice, once with a parameter of `left`, and once with a parameter of `right`.) This returns a {{domxref("VREyeParameters")}} object for each eye. @@ -330,10 +346,10 @@ The field of view created is a pyramid shape, the apex of which is emanating fro You could check whether the user has a suitable field of view for your app, and if not, set a new field of view using {{domxref("HMDVRDevice.setFieldOfView")}} method. A simple function to handle this might look like so: ```js -function setCustomFOV(up,right,down,left) { - var testFOV = new VRFieldOfView(up,right,down,left); +function setCustomFOV(up, right, down, left) { + var testFOV = new VRFieldOfView(up, right, down, left); - gHMD.setFieldOfView(testFOV,testFOV,0.01,10000.0); + gHMD.setFieldOfView(testFOV, testFOV, 0.01, 10000.0); } ``` diff --git a/files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.md b/files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.md index ae3633fd45755a..c1f0669f4a3e16 100644 --- a/files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.md +++ b/files/zh-cn/web/api/webvr_api/using_vr_controllers_with_webvr/index.md @@ -43,11 +43,12 @@ The first notable code is as follows: ```js var initialRun = true; -if(navigator.getVRDisplays && navigator.getGamepads) { - info.textContent = 'WebVR API and Gamepad API supported.' +if (navigator.getVRDisplays && navigator.getGamepads) { + info.textContent = "WebVR API and Gamepad API supported."; reportDisplays(); } else { - info.textContent = 'WebVR API and/or Gamepad API not supported by this browser.' + info.textContent = + "WebVR API and/or Gamepad API not supported by this browser."; } ``` @@ -55,20 +56,30 @@ Here we first use a tracking variable, `initialRun`, to note that this is the fi ```js function reportDisplays() { - navigator.getVRDisplays().then(function(displays) { - console.log(displays.length + ' displays'); - for(var i = 0; i < displays.length; i++) { + navigator.getVRDisplays().then(function (displays) { + console.log(displays.length + " displays"); + for (var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a VRDisplayCapabilities object - var listItem = document.createElement('li'); - listItem.innerHTML = 'Display ' + (i+1) + '' - + '
VR Display ID: ' + displays[i].displayId - + '
VR Display Name: ' + displays[i].displayName - + '
Display can present content: ' + cap.canPresent - + '
Display is separate from the computer\'s main display: ' + cap.hasExternalDisplay - + '
Display can return position info: ' + cap.hasPosition - + '
Display can return orientation info: ' + cap.hasOrientation - + '
Display max layers: ' + cap.maxLayers; + var listItem = document.createElement("li"); + listItem.innerHTML = + "Display " + + (i + 1) + + "" + + "
VR Display ID: " + + displays[i].displayId + + "
VR Display Name: " + + displays[i].displayName + + "
Display can present content: " + + cap.canPresent + + "
Display is separate from the computer's main display: " + + cap.hasExternalDisplay + + "
Display can return position info: " + + cap.hasPosition + + "
Display can return orientation info: " + + cap.hasOrientation + + "
Display max layers: " + + cap.maxLayers; list.appendChild(listItem); } @@ -88,18 +99,28 @@ The `reportGamepads()` function looks like this: ```js function reportGamepads() { - var gamepads = navigator.getGamepads(); - console.log(gamepads.length + ' controllers'); - for(var i = 0; i < gamepads.length; ++i) { - var gp = gamepads[i]; - var listItem = document.createElement('li'); - listItem.classList = 'gamepad'; - listItem.innerHTML = 'Gamepad ' + gp.index + ' (' + gp.id + ')' - + '
Associated with VR Display ID: ' + gp.displayId - + '
Gamepad associated with which hand: ' + gp.hand - + '
Available haptic actuators: ' + gp.hapticActuators.length - + '
Gamepad can return position info: ' + gp.pose.hasPosition - + '
Gamepad can return orientation info: ' + gp.pose.hasOrientation; + var gamepads = navigator.getGamepads(); + console.log(gamepads.length + " controllers"); + for (var i = 0; i < gamepads.length; ++i) { + var gp = gamepads[i]; + var listItem = document.createElement("li"); + listItem.classList = "gamepad"; + listItem.innerHTML = + "Gamepad " + + gp.index + + " (" + + gp.id + + ")" + + "
Associated with VR Display ID: " + + gp.displayId + + "
Gamepad associated with which hand: " + + gp.hand + + "
Available haptic actuators: " + + gp.hapticActuators.length + + "
Gamepad can return position info: " + + gp.pose.hasPosition + + "
Gamepad can return orientation info: " + + gp.pose.hasOrientation; list.appendChild(listItem); } initialRun = false; @@ -126,12 +147,12 @@ At the end of our example we first include the `removeGamepads()` function: ```js function removeGamepads() { - var gpLi = document.querySelectorAll('.gamepad'); - for(var i = 0; i < gpLi.length; i++) { + var gpLi = document.querySelectorAll(".gamepad"); + for (var i = 0; i < gpLi.length; i++) { list.removeChild(gpLi[i]); - } + } - reportGamepads(); + reportGamepads(); } ``` @@ -140,15 +161,15 @@ This function simply grabs references to all list items with a class name of `ga `removeGamepads()` will be run each time a gamepad is connected or disconnected, via the following event handlers: ```js -window.addEventListener('gamepadconnected', function(e) { - info.textContent = 'Gamepad ' + e.gamepad.index + ' connected.'; - if(!initialRun) { - setTimeout(removeGamepads, 1000); +window.addEventListener("gamepadconnected", function (e) { + info.textContent = "Gamepad " + e.gamepad.index + " connected."; + if (!initialRun) { + setTimeout(removeGamepads, 1000); } }); -window.addEventListener('gamepaddisconnected', function(e) { - info.textContent = 'Gamepad ' + e.gamepad.index + ' disconnected.'; +window.addEventListener("gamepaddisconnected", function (e) { + info.textContent = "Gamepad " + e.gamepad.index + " disconnected."; setTimeout(removeGamepads, 1000); }); ``` @@ -173,11 +194,11 @@ Inside the `drawVRScene()` function, you'll find this bit of code: var gamepads = navigator.getGamepads(); var gp = gamepads[0]; -if(gp) { +if (gp) { var gpPose = gp.pose; var curPos = gpPose.position; var curOrient = gpPose.orientation; - if(poseStatsDisplayed) { + if (poseStatsDisplayed) { displayPoseStats(gpPose); } } @@ -190,24 +211,16 @@ The next thing we do is to get the {{domxref("GamepadPose")}} object for the con Slightly later in the code, you can find this block: ```js -if(gp && gpPose.hasPosition) { - mvTranslate([ - 0.0 + (curPos[0] * 15) - (curOrient[1] * 15), - 0.0 + (curPos[1] * 15) + (curOrient[0] * 15), - -15.0 + (curPos[2] * 25) - ]); -} else if(gp) { +if (gp && gpPose.hasPosition) { mvTranslate([ - 0.0 + (curOrient[1] * 15), - 0.0 + (curOrient[0] * 15), - -15.0 - ]); + 0.0 + curPos[0] * 15 - curOrient[1] * 15, + 0.0 + curPos[1] * 15 + curOrient[0] * 15, + -15.0 + curPos[2] * 25, + ]); +} else if (gp) { + mvTranslate([0.0 + curOrient[1] * 15, 0.0 + curOrient[0] * 15, -15.0]); } else { - mvTranslate([ - 0.0, - 0.0, - -15.0 - ]); + mvTranslate([0.0, 0.0, -15.0]); } ``` @@ -228,31 +241,67 @@ function displayPoseStats(pose) { var angVel = pose.angularVelocity; var angAcc = pose.angularAcceleration; - if(pose.hasPosition) { - posStats.textContent = 'Position: x ' + pos[0].toFixed(3) + ', y ' + pos[1].toFixed(3) + ', z ' + pos[2].toFixed(3); + if (pose.hasPosition) { + posStats.textContent = + "Position: x " + + pos[0].toFixed(3) + + ", y " + + pos[1].toFixed(3) + + ", z " + + pos[2].toFixed(3); } else { - posStats.textContent = 'Position not reported'; + posStats.textContent = "Position not reported"; } - if(pose.hasOrientation) { - orientStats.textContent = 'Orientation: x ' + orient[0].toFixed(3) + ', y ' + orient[1].toFixed(3) + ', z ' + orient[2].toFixed(3); + if (pose.hasOrientation) { + orientStats.textContent = + "Orientation: x " + + orient[0].toFixed(3) + + ", y " + + orient[1].toFixed(3) + + ", z " + + orient[2].toFixed(3); } else { - orientStats.textContent = 'Orientation not reported'; + orientStats.textContent = "Orientation not reported"; } - linVelStats.textContent = 'Linear velocity: x ' + linVel[0].toFixed(3) + ', y ' + linVel[1].toFixed(3) + ', z ' + linVel[2].toFixed(3); - angVelStats.textContent = 'Angular velocity: x ' + angVel[0].toFixed(3) + ', y ' + angVel[1].toFixed(3) + ', z ' + angVel[2].toFixed(3); - - if(linAcc) { - linAccStats.textContent = 'Linear acceleration: x ' + linAcc[0].toFixed(3) + ', y ' + linAcc[1].toFixed(3) + ', z ' + linAcc[2].toFixed(3); + linVelStats.textContent = + "Linear velocity: x " + + linVel[0].toFixed(3) + + ", y " + + linVel[1].toFixed(3) + + ", z " + + linVel[2].toFixed(3); + angVelStats.textContent = + "Angular velocity: x " + + angVel[0].toFixed(3) + + ", y " + + angVel[1].toFixed(3) + + ", z " + + angVel[2].toFixed(3); + + if (linAcc) { + linAccStats.textContent = + "Linear acceleration: x " + + linAcc[0].toFixed(3) + + ", y " + + linAcc[1].toFixed(3) + + ", z " + + linAcc[2].toFixed(3); } else { - linAccStats.textContent = 'Linear acceleration not reported'; + linAccStats.textContent = "Linear acceleration not reported"; } - if(angAcc) { - angAccStats.textContent = 'Angular acceleration: x ' + angAcc[0].toFixed(3) + ', y ' + angAcc[1].toFixed(3) + ', z ' + angAcc[2].toFixed(3); + if (angAcc) { + angAccStats.textContent = + "Angular acceleration: x " + + angAcc[0].toFixed(3) + + ", y " + + angAcc[1].toFixed(3) + + ", z " + + angAcc[2].toFixed(3); } else { - angAccStats.textContent = 'Angular acceleration not reported'; + angAccStats.textContent = "Angular acceleration not reported"; } } ``` diff --git a/files/zh-cn/web/api/webvtt_api/index.md b/files/zh-cn/web/api/webvtt_api/index.md index 6ad2abab58b163..1c07a7cf9dddfc 100644 --- a/files/zh-cn/web/api/webvtt_api/index.md +++ b/files/zh-cn/web/api/webvtt_api/index.md @@ -445,7 +445,7 @@ cue 文本的有效内容不能包含 `-->` 字符串、和号字符(`&`)或 - 时间戳标签 - - : 时间戳必须大于 cue 开始的时间戳,大于在 cue 有效内容中任意之前的时间戳,并且小于 cue 结束的时间戳。*活动的文本*(active text)是指当前时间戳和下一个时间戳之间的文本或者如果有效内容中没有其他时间戳,则一直到有效内容末尾的文本。有效内容中*活动的文本*之前的任何文本都是*之前已出现的文本*(previous text)。*活动的文本*之后的文本都是*未来即将出现的文本*(future text)。这启用了 karaoke 风格的字幕。 + - : 时间戳必须大于 cue 开始的时间戳,大于在 cue 有效内容中任意之前的时间戳,并且小于 cue 结束的时间戳。_活动的文本_(active text)是指当前时间戳和下一个时间戳之间的文本或者如果有效内容中没有其他时间戳,则一直到有效内容末尾的文本。有效内容中*活动的文本*之前的任何文本都是*之前已出现的文本*(previous text)。*活动的文本*之后的文本都是*未来即将出现的文本*(future text)。这启用了 karaoke 风格的字幕。 ```plain 1 @@ -521,7 +521,7 @@ cue 文本的有效内容不能包含 `-->` 字符串、和号字符(`&`)或 ## 方法和属性 - WebVTT 使用的方法是那些用于更改 cue 或者 region 的方法,因为两个接口的属性都不同,我们可以对它们进行分类,以更好地理解关于 WebVTT 中的每个接口: +WebVTT 使用的方法是那些用于更改 cue 或者 region 的方法,因为两个接口的属性都不同,我们可以对它们进行分类,以更好地理解关于 WebVTT 中的每个接口: ### VTTCue diff --git a/files/zh-cn/web/api/webxr_device_api/index.md b/files/zh-cn/web/api/webxr_device_api/index.md index 310a7007866bf8..2cee1c8f925598 100644 --- a/files/zh-cn/web/api/webxr_device_api/index.md +++ b/files/zh-cn/web/api/webxr_device_api/index.md @@ -48,21 +48,21 @@ WebXR-兼容性设备包括沉浸式 3D 运动和定位跟踪耳机,通过框 1. 检查用户的设备和浏览器是否都能够呈现您想要提供的 XR 体验。 - 1. 确保 WebXR API 可用;如果 {{domxref("navigator.xr")}} 未定义,则可以判断用户的浏览器和/或设备不支持 WebXR。如果不支持,请禁用用于激活 XR 功能的任何用户界面,并中止任何进入 XR 模式的尝试。 - 2. 调用 {{DOMxRef("XR.isSessionSupported","navigator.xr.isSessionSupported()")}}, 指定要提供的 WebXR 体验模式:`inline`, `immersive-vr`, 或 `immersive-ar`, 以确定您希望提供的会话类型是否可用。 - 3. 如果要使用的会话类型可用,请向用户提供适当的界面以允许他们激活它。 + 1. 确保 WebXR API 可用;如果 {{domxref("navigator.xr")}} 未定义,则可以判断用户的浏览器和/或设备不支持 WebXR。如果不支持,请禁用用于激活 XR 功能的任何用户界面,并中止任何进入 XR 模式的尝试。 + 2. 调用 {{DOMxRef("XR.isSessionSupported","navigator.xr.isSessionSupported()")}}, 指定要提供的 WebXR 体验模式:`inline`, `immersive-vr`, 或 `immersive-ar`, 以确定您希望提供的会话类型是否可用。 + 3. 如果要使用的会话类型可用,请向用户提供适当的界面以允许他们激活它。 2. 当用户通过上述的界面开启了 WebXR 功能后,通过调用 {{DOMxRef("XR.requestSession","navigator.xr.requestSession()")}},也是指定使用的模式为以下三种之一: `inline`, `immersive-vr`, 或 `immersive-ar`后,可以将一个 {{DOMxRef("XRSession")}} 设定在期望的模式下。 3. 当 `requestSession()` 返回的 promise 被 resolve 后,使用新的 {{domxref("XRSession")}} 在整个 WebXR 体验期间运行帧循环。 - 1. 调用 {{domxref("XRSession")}} 的 {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} 方法,以调度 XR 设备的首帧渲染。 - 2. 每一个 `requestAnimationFrame()` 的回调都需要使用 WebGL 渲染已提供信息的 3D 世界中的物体。 - 3. 持续在回调中调用 {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} 保证每一帧都成功地按顺序渲染。 + 1. 调用 {{domxref("XRSession")}} 的 {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} 方法,以调度 XR 设备的首帧渲染。 + 2. 每一个 `requestAnimationFrame()` 的回调都需要使用 WebGL 渲染已提供信息的 3D 世界中的物体。 + 3. 持续在回调中调用 {{DOMxRef("XRSession.requestAnimationFrame", "requestAnimationFrame()")}} 保证每一帧都成功地按顺序渲染。 4. 当需要结束 XR 会话的时候;或者用户主动退出 XR 模式。 - 1. 通过调用 {{DOMxRef("XRSession.end", "XRSession.end()")}} 可手动结束 XR 会话。 - 2. 无论通过何种方式(开发者、用户或者浏览器)终止会话,{{domxref("XRSession")}} 的 {{domxref("XRSession.end_event", "end")}} 事件都会接收到通知。 + 1. 通过调用 {{DOMxRef("XRSession.end", "XRSession.end()")}} 可手动结束 XR 会话。 + 2. 无论通过何种方式(开发者、用户或者浏览器)终止会话,{{domxref("XRSession")}} 的 {{domxref("XRSession.end_event", "end")}} 事件都会接收到通知。 ### 获取许可与安全性 diff --git a/files/zh-cn/web/api/wheelevent/deltamode/index.md b/files/zh-cn/web/api/wheelevent/deltamode/index.md index 56acfec8f9ddc8..621f6094cbd0c1 100644 --- a/files/zh-cn/web/api/wheelevent/deltamode/index.md +++ b/files/zh-cn/web/api/wheelevent/deltamode/index.md @@ -22,7 +22,10 @@ var unit = event.deltaMode; ## 例子 ```js -var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaX": 4, "deltaMode": 0}); +var syntheticEvent = new WheelEvent("syntheticWheel", { + deltaX: 4, + deltaMode: 0, +}); console.log(syntheticEvent.deltaMode); ``` diff --git a/files/zh-cn/web/api/wheelevent/deltax/index.md b/files/zh-cn/web/api/wheelevent/deltax/index.md index dc37f5d0d47063..2d0b3dbf2b80a3 100644 --- a/files/zh-cn/web/api/wheelevent/deltax/index.md +++ b/files/zh-cn/web/api/wheelevent/deltax/index.md @@ -16,7 +16,10 @@ var dX = event.deltaX; ## 例子 ```js -var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaX": 4, "deltaMode": 0}); +var syntheticEvent = new WheelEvent("syntheticWheel", { + deltaX: 4, + deltaMode: 0, +}); console.log(syntheticEvent.deltaX); ``` diff --git a/files/zh-cn/web/api/wheelevent/deltay/index.md b/files/zh-cn/web/api/wheelevent/deltay/index.md index c071092c719420..0e91fbec206170 100644 --- a/files/zh-cn/web/api/wheelevent/deltay/index.md +++ b/files/zh-cn/web/api/wheelevent/deltay/index.md @@ -16,7 +16,10 @@ var dY = event.deltaY; ## 例子 ```js -var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaY": 4, "deltaMode": 0}); +var syntheticEvent = new WheelEvent("syntheticWheel", { + deltaY: 4, + deltaMode: 0, +}); console.log(syntheticEvent.deltaY); ``` diff --git a/files/zh-cn/web/api/wheelevent/deltaz/index.md b/files/zh-cn/web/api/wheelevent/deltaz/index.md index 252ae9e8d0d427..0e2fdeeed86953 100644 --- a/files/zh-cn/web/api/wheelevent/deltaz/index.md +++ b/files/zh-cn/web/api/wheelevent/deltaz/index.md @@ -16,7 +16,10 @@ var dZ = event.deltaZ; ## 例子 ```js -var syntheticEvent = new WheelEvent("syntheticWheel", {"deltaZ": 4, "deltaMode": 0}); +var syntheticEvent = new WheelEvent("syntheticWheel", { + deltaZ: 4, + deltaMode: 0, +}); console.log(syntheticEvent.deltaZ); ``` diff --git a/files/zh-cn/web/api/wheelevent/index.md b/files/zh-cn/web/api/wheelevent/index.md index 7791c92abd887c..00ec031126606d 100644 --- a/files/zh-cn/web/api/wheelevent/index.md +++ b/files/zh-cn/web/api/wheelevent/index.md @@ -29,13 +29,14 @@ _该接口继承了父接口 {{domxref("MouseEvent")}}、{{domxref("UIEvent")}} - {{domxref("WheelEvent.deltaZ")}} {{readonlyinline}} - : 返回一个 `double` 值,该值表示滚轮的 z 轴方向上的滚动量。 - {{domxref("WheelEvent.deltaMode")}} {{readonlyinline}} + - : 返回一个 `unsigned long` 值,该值表示上述各 `delta*` 的值的单位。允许的值如下: - | 常量 | 值 | 描述 | - | ---------------------------- | ------ | ------------------------------------------------------------------- | - | `WheelEvent.DOM_DELTA_PIXEL` | `0x00` | `delta*` 的单位为像素。 | - | `WheelEvent.DOM_DELTA_LINE` | `0x01` | `delta*` 单位为行。每一次点击鼠标都会滚动一行内容,行高的计算取决于浏览器。 | - | `WheelEvent.DOM_DELTA_PAGE` | `0x02` | `delta*` 单位为页。每一次点击鼠标都会滚动一页内容。 | + | 常量 | 值 | 描述 | + | ---------------------------- | ------ | --------------------------------------------------------------------------- | + | `WheelEvent.DOM_DELTA_PIXEL` | `0x00` | `delta*` 的单位为像素。 | + | `WheelEvent.DOM_DELTA_LINE` | `0x01` | `delta*` 单位为行。每一次点击鼠标都会滚动一行内容,行高的计算取决于浏览器。 | + | `WheelEvent.DOM_DELTA_PAGE` | `0x02` | `delta*` 单位为页。每一次点击鼠标都会滚动一页内容。 | - {{DOMxRef("WheelEvent.wheelDelta")}} {{ReadOnlyInline}} {{deprecated_inline}} - : 返回一个整数(32 位),表示以像素为单位的距离。 diff --git a/files/zh-cn/web/api/window/afterprint_event/index.md b/files/zh-cn/web/api/window/afterprint_event/index.md index 893d73e7890d1a..100cdb0a0d98cc 100644 --- a/files/zh-cn/web/api/window/afterprint_event/index.md +++ b/files/zh-cn/web/api/window/afterprint_event/index.md @@ -22,20 +22,20 @@ slug: Web/API/Window/afterprint_event ## 属性 -| Property | Type | Description | -| ------------------------------------- | ------------------------------------ | ------------------------------------------------------ | +| Property | Type | Description | +| ------------------------------- | -------------------------- | ------------------------------------------------------ | | `target` {{readonlyInline}} | {{domxref("EventTarget")}} | The event target (the topmost target in the DOM tree). | -| `type` {{readonlyInline}} | {{domxref("DOMString")}} | The type of event. | -| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event normally bubbles or not. | -| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event is cancellable or not. | +| `type` {{readonlyInline}} | {{domxref("DOMString")}} | The type of event. | +| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event normally bubbles or not. | +| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event is cancellable or not. | ## 例子 使用 `addEventListener()`: ```js -window.addEventListener('afterprint', (event) => { - console.log('After print'); +window.addEventListener("afterprint", (event) => { + console.log("After print"); }); ``` @@ -43,7 +43,7 @@ window.addEventListener('afterprint', (event) => { ```js window.onafterprint = (event) => { - console.log('After print'); + console.log("After print"); }; ``` diff --git a/files/zh-cn/web/api/window/appinstalled_event/index.md b/files/zh-cn/web/api/window/appinstalled_event/index.md index 5ecd408c5a8a07..152c8cbcdf7325 100644 --- a/files/zh-cn/web/api/window/appinstalled_event/index.md +++ b/files/zh-cn/web/api/window/appinstalled_event/index.md @@ -16,8 +16,8 @@ window.onappinstalled = function(event) { ... }; ## 示例 ```js -window.onappinstalled = function(ev) { - console.log('The application was installed.'); +window.onappinstalled = function (ev) { + console.log("The application was installed."); }; ``` diff --git a/files/zh-cn/web/api/window/back/index.md b/files/zh-cn/web/api/window/back/index.md index fd006e45ae11e4..f36b74b298c957 100644 --- a/files/zh-cn/web/api/window/back/index.md +++ b/files/zh-cn/web/api/window/back/index.md @@ -19,6 +19,6 @@ window.back() ```js function goBack() { - if ( canGoBack ) window.back(); + if (canGoBack) window.back(); } ``` diff --git a/files/zh-cn/web/api/window/beforeinstallprompt_event/index.md b/files/zh-cn/web/api/window/beforeinstallprompt_event/index.md index 7debfd7a531a00..ab64fa4bd1f62f 100644 --- a/files/zh-cn/web/api/window/beforeinstallprompt_event/index.md +++ b/files/zh-cn/web/api/window/beforeinstallprompt_event/index.md @@ -21,11 +21,11 @@ The following example uses the beforeinstallprompt function to verify that it is ```js let isTooSoon = true; -window.addEventListener("beforeinstallprompt", function(e) { +window.addEventListener("beforeinstallprompt", function (e) { if (isTooSoon) { e.preventDefault(); // Prevents prompt display // Prompt later instead: - setTimeout(function() { + setTimeout(function () { isTooSoon = false; e.prompt(); // Shows prompt }, 10000); diff --git a/files/zh-cn/web/api/window/beforeprint_event/index.md b/files/zh-cn/web/api/window/beforeprint_event/index.md index b5698c3abbbddb..a45db0e11e90c5 100644 --- a/files/zh-cn/web/api/window/beforeprint_event/index.md +++ b/files/zh-cn/web/api/window/beforeprint_event/index.md @@ -22,20 +22,20 @@ slug: Web/API/Window/beforeprint_event ## 属性 -| 属性 | 类型 | 描述 | -| ------------------------------------- | ------------------------------------ | ------------------------------- | +| 属性 | 类型 | 描述 | +| ------------------------------- | -------------------------- | ------------------------------- | | `target` {{readonlyInline}} | {{domxref("EventTarget")}} | 事件目标 (DOM 树中的最顶层目标) | -| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 时间类型 | -| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否冒泡 | -| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否可取消 | +| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 时间类型 | +| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否冒泡 | +| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否可取消 | ## 样例 使用 `addEventListener()`: ```js -window.addEventListener('beforeprint', (event) => { - console.log('Before print'); +window.addEventListener("beforeprint", (event) => { + console.log("Before print"); }); ``` @@ -43,7 +43,7 @@ window.addEventListener('beforeprint', (event) => { ```js window.onbeforeprint = (event) => { - console.log('Before print'); + console.log("Before print"); }; ``` diff --git a/files/zh-cn/web/api/window/beforeunload_event/index.md b/files/zh-cn/web/api/window/beforeunload_event/index.md index 8d9b292d7ca211..81a40740262869 100644 --- a/files/zh-cn/web/api/window/beforeunload_event/index.md +++ b/files/zh-cn/web/api/window/beforeunload_event/index.md @@ -1,5 +1,5 @@ --- -title: 'Window: beforeunload event' +title: "Window: beforeunload event" slug: Web/API/Window/beforeunload_event --- @@ -52,11 +52,11 @@ HTML 规范指出在此事件中调用{{domxref("window.alert()")}},{{domxref( HTML 规范指出作者应该使用 {{domxref("Event.preventDefault()")}} 而非 {{domxref("Event.returnValue")}},然而,不是所有浏览器都支持这么做。 ```js -window.addEventListener('beforeunload', (event) => { +window.addEventListener("beforeunload", (event) => { // Cancel the event as stated by the standard. event.preventDefault(); // Chrome requires returnValue to be set. - event.returnValue = ''; + event.returnValue = ""; }); ``` diff --git a/files/zh-cn/web/api/window/blur_event/index.md b/files/zh-cn/web/api/window/blur_event/index.md index bef28f9aeaf6af..9125ff1eca0a31 100644 --- a/files/zh-cn/web/api/window/blur_event/index.md +++ b/files/zh-cn/web/api/window/blur_event/index.md @@ -1,5 +1,5 @@ --- -title: 'Window: blur event' +title: "Window: blur event" slug: Web/API/Window/blur_event --- @@ -65,19 +65,20 @@ slug: Web/API/Window/blur_event ```js function pause() { - document.body.classList.add('paused'); - log.textContent = 'FOCUS LOST!'; + document.body.classList.add("paused"); + log.textContent = "FOCUS LOST!"; } function play() { - document.body.classList.remove('paused'); - log.textContent = 'This document has focus. Click outside the document to lose focus.'; + document.body.classList.remove("paused"); + log.textContent = + "This document has focus. Click outside the document to lose focus."; } -const log = document.getElementById('log'); +const log = document.getElementById("log"); -window.addEventListener('blur', pause); -window.addEventListener('focus', play); +window.addEventListener("blur", pause); +window.addEventListener("focus", play); ``` #### 结果 diff --git a/files/zh-cn/web/api/window/clearimmediate/index.md b/files/zh-cn/web/api/window/clearimmediate/index.md index 3f3afd57c9b854..e06cf638b70556 100644 --- a/files/zh-cn/web/api/window/clearimmediate/index.md +++ b/files/zh-cn/web/api/window/clearimmediate/index.md @@ -14,7 +14,7 @@ slug: Web/API/Window/clearImmediate ## 语法 ```js -window.clearImmediate(immediateID) +window.clearImmediate(immediateID); ``` 这里的 immediateID 是由{{ domxref("window.setImmediate") }}返回的。 diff --git a/files/zh-cn/web/api/window/close/index.md b/files/zh-cn/web/api/window/close/index.md index 5f7b6d2e955ca1..ac4ab58e0bb11e 100644 --- a/files/zh-cn/web/api/window/close/index.md +++ b/files/zh-cn/web/api/window/close/index.md @@ -28,7 +28,7 @@ window.close(); var openedWindow; function openWindow() { - openedWindow = window.open('moreinfo.htm'); + openedWindow = window.open("moreinfo.htm"); } function closeOpenedWindow() { diff --git a/files/zh-cn/web/api/window/closed/index.md b/files/zh-cn/web/api/window/closed/index.md index 1be448b29d5a2c..cd26b6e2dc4eb3 100644 --- a/files/zh-cn/web/api/window/closed/index.md +++ b/files/zh-cn/web/api/window/closed/index.md @@ -50,7 +50,7 @@ function refreshPopupWindow() { popupWindow.location.reload(true); } else { // Open a new popup window - popupWindow = window.open("popup.html","dataWindow"); + popupWindow = window.open("popup.html", "dataWindow"); } } ``` diff --git a/files/zh-cn/web/api/window/customelements/index.md b/files/zh-cn/web/api/window/customelements/index.md index 32e9e5741e90c6..3cc55a46fcf794 100644 --- a/files/zh-cn/web/api/window/customelements/index.md +++ b/files/zh-cn/web/api/window/customelements/index.md @@ -13,23 +13,26 @@ slug: Web/API/Window/customElements ```js let customElementRegistry = window.customElements; -customElementRegistry.define('my-custom-element', MyCustomElement); +customElementRegistry.define("my-custom-element", MyCustomElement); ``` However, it is usually shortened to something like the following: ```js -customElements.define('element-details', +customElements.define( + "element-details", class extends HTMLElement { constructor() { super(); - const template = document - .getElementById('element-details-template') - .content; - const shadowRoot = this.attachShadow({mode: 'open'}) - .appendChild(template.cloneNode(true)); - } -}); + const template = document.getElementById( + "element-details-template", + ).content; + const shadowRoot = this.attachShadow({ mode: "open" }).appendChild( + template.cloneNode(true), + ); + } + }, +); ``` 参阅我们的 [web-components-examples](https://github.com/mdn/web-components-examples/) 获取更多有用的例子。 diff --git a/files/zh-cn/web/api/window/deviceorientation_event/index.md b/files/zh-cn/web/api/window/deviceorientation_event/index.md index 693439f4fdf566..2922c1f405fbd6 100644 --- a/files/zh-cn/web/api/window/deviceorientation_event/index.md +++ b/files/zh-cn/web/api/window/deviceorientation_event/index.md @@ -1,5 +1,5 @@ --- -title: 'Window:deviceorientation 事件' +title: "Window:deviceorientation 事件" slug: Web/API/Window/deviceorientation_event --- @@ -16,9 +16,9 @@ slug: Web/API/Window/deviceorientation_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 方法中使用事件名称,或使用事件处理器属性。 ```js -addEventListener('deviceorientation', event => { }); +addEventListener("deviceorientation", (event) => {}); -ondeviceorientation = event => { }; +ondeviceorientation = (event) => {}; ``` ## 事件类型 @@ -46,20 +46,28 @@ ondeviceorientation = event => { }; ```js if (window.DeviceOrientationEvent) { - window.addEventListener("deviceorientation", function(event) { - // alpha: rotation around z-axis - var rotateDegrees = event.alpha; - // gamma: left to right - var leftToRight = event.gamma; - // beta: front back motion - var frontToBack = event.beta; - - handleOrientationEvent(frontToBack, leftToRight, rotateDegrees); - }, true); + window.addEventListener( + "deviceorientation", + function (event) { + // alpha: rotation around z-axis + var rotateDegrees = event.alpha; + // gamma: left to right + var leftToRight = event.gamma; + // beta: front back motion + var frontToBack = event.beta; + + handleOrientationEvent(frontToBack, leftToRight, rotateDegrees); + }, + true, + ); } -var handleOrientationEvent = function(frontToBack, leftToRight, rotateDegrees) { - // do something amazing +var handleOrientationEvent = function ( + frontToBack, + leftToRight, + rotateDegrees, +) { + // do something amazing }; ``` diff --git a/files/zh-cn/web/api/window/devicepixelratio/index.md b/files/zh-cn/web/api/window/devicepixelratio/index.md index c1a23fcefd3d98..704eb46e273b73 100644 --- a/files/zh-cn/web/api/window/devicepixelratio/index.md +++ b/files/zh-cn/web/api/window/devicepixelratio/index.md @@ -36,8 +36,8 @@ value = window.devicePixelRatio; #### JavaScript ```js -var canvas = document.getElementById('canvas'); -var ctx = canvas.getContext('2d'); +var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); // Set display size (css pixels). var size = 200; @@ -55,9 +55,9 @@ ctx.scale(scale, scale); ctx.fillStyle = "#bada55"; ctx.fillRect(10, 10, 300, 300); ctx.fillStyle = "#ffffff"; -ctx.font = '18px Arial'; -ctx.textAlign = 'center'; -ctx.textBaseline = 'middle'; +ctx.font = "18px Arial"; +ctx.textAlign = "center"; +ctx.textBaseline = "middle"; var x = size / 2; var y = size / 2; @@ -84,7 +84,7 @@ const updatePixelRatio = () => { let pr = window.devicePixelRatio; let prString = (pr * 100).toFixed(0); pixelRatioBox.innerText = `${prString}% (${pr.toFixed(2)})`; -} +}; updatePixelRatio(); @@ -104,12 +104,14 @@ HTML 将创建包含说明的框和将显示当前像素比率信息的`pixel-ra ```html
-

This example demonstrates the effect of zooming the page in - and out (or moving it to a screen with a different scaling - factor) on the value of the property Window.devicePixelRatio. - Try it and watch what happens!

+

+ This example demonstrates the effect of zooming the page in and out (or + moving it to a screen with a different scaling factor) on the value of the + property Window.devicePixelRatio. Try it and watch what + happens! +

-
+
``` @@ -117,7 +119,9 @@ HTML 将创建包含说明的框和将显示当前像素比率信息的`pixel-ra ```css body { - font: 22px arial, sans-serif; + font: + 22px arial, + sans-serif; } .container { diff --git a/files/zh-cn/web/api/window/document/index.md b/files/zh-cn/web/api/window/document/index.md index ba1dd0d0643d88..5ba6ca1a4bd7dc 100644 --- a/files/zh-cn/web/api/window/document/index.md +++ b/files/zh-cn/web/api/window/document/index.md @@ -12,7 +12,7 @@ slug: Web/API/Window/document ## 语法 ```js -doc = window.document +doc = window.document; ``` ## 参数 @@ -22,19 +22,17 @@ doc = window.document ## 例子 ```html - + - - Hello, World! - - - - - - + + Hello, World! + + + + ``` diff --git a/files/zh-cn/web/api/window/domcontentloaded_event/index.md b/files/zh-cn/web/api/window/domcontentloaded_event/index.md index bc4278b03e5b24..93511e4643f56d 100644 --- a/files/zh-cn/web/api/window/domcontentloaded_event/index.md +++ b/files/zh-cn/web/api/window/domcontentloaded_event/index.md @@ -50,12 +50,12 @@ document.addEventListener('DOMContentLoaded',function(){ ## 属性 -| 属性 | 类型 | 描述 | -| ------------------------------------- | ------------------------------------ | -------------------------------------------- | +| 属性 | 类型 | 描述 | +| ------------------------------- | -------------------------- | -------------------------------------------- | | `target` {{readonlyInline}} | {{domxref("EventTarget")}} | 产生该事件的对象 (DOM 树中最顶级的那个对象). | -| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 事件类型。 | -| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 该事件是否冒泡。 | -| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 该事件是否可取消默认行为。 | +| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 事件类型。 | +| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 该事件是否冒泡。 | +| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 该事件是否可取消默认行为。 | ## 示例 diff --git a/files/zh-cn/web/api/window/error_event/index.md b/files/zh-cn/web/api/window/error_event/index.md index 38fbb361dcc2e2..10525a736de019 100644 --- a/files/zh-cn/web/api/window/error_event/index.md +++ b/files/zh-cn/web/api/window/error_event/index.md @@ -1,5 +1,5 @@ --- -title: 'Window: error event' +title: "Window: error event" slug: Web/API/Window/error_event --- @@ -75,13 +75,14 @@ body { resize: none; } -label, button { +label, +button { display: block; } button { height: 2rem; - margin: .5rem; + margin: 0.5rem; } img { @@ -93,17 +94,17 @@ img { #### JS ```js -const log = document.querySelector('.event-log-contents'); +const log = document.querySelector(".event-log-contents"); -window.addEventListener('error', (event) => { - log.textContent = log.textContent + `${event.type}: ${event.message}\n`; - console.log(event) +window.addEventListener("error", (event) => { + log.textContent = log.textContent + `${event.type}: ${event.message}\n`; + console.log(event); }); -const scriptError = document.querySelector('#script-error'); -scriptError.addEventListener('click', () => { - const badCode = 'const s;'; - eval(badCode); +const scriptError = document.querySelector("#script-error"); +scriptError.addEventListener("click", () => { + const badCode = "const s;"; + eval(badCode); }); ``` diff --git a/files/zh-cn/web/api/window/focus/index.md b/files/zh-cn/web/api/window/focus/index.md index 8d213acdfae6e3..2e1ba72c1ca63a 100644 --- a/files/zh-cn/web/api/window/focus/index.md +++ b/files/zh-cn/web/api/window/focus/index.md @@ -12,13 +12,15 @@ slug: Web/API/Window/focus ## 语法 ```js -window.focus() +window.focus(); ``` ## 示例 ```js -if (clicked) { window.focus(); } +if (clicked) { + window.focus(); +} ``` ## 规范 diff --git a/files/zh-cn/web/api/window/focus_event/index.md b/files/zh-cn/web/api/window/focus_event/index.md index 6cc7c8dc90c92a..6dfbca00166a23 100644 --- a/files/zh-cn/web/api/window/focus_event/index.md +++ b/files/zh-cn/web/api/window/focus_event/index.md @@ -1,5 +1,5 @@ --- -title: 'Window: focus event' +title: "Window: focus event" slug: Web/API/Window/focus_event --- @@ -66,19 +66,20 @@ slug: Web/API/Window/focus_event ```js function pause() { - document.body.classList.add('paused'); - log.textContent = 'FOCUS LOST!'; + document.body.classList.add("paused"); + log.textContent = "FOCUS LOST!"; } function play() { - document.body.classList.remove('paused'); - log.textContent = 'This document has focus. Click outside the document to lose focus.'; + document.body.classList.remove("paused"); + log.textContent = + "This document has focus. Click outside the document to lose focus."; } -const log = document.getElementById('log'); +const log = document.getElementById("log"); -window.addEventListener('blur', pause); -window.addEventListener('focus', play); +window.addEventListener("blur", pause); +window.addEventListener("focus", play); ``` #### 结果 diff --git a/files/zh-cn/web/api/window/frames/index.md b/files/zh-cn/web/api/window/frames/index.md index 92b32091c363ad..df360e171ffc83 100644 --- a/files/zh-cn/web/api/window/frames/index.md +++ b/files/zh-cn/web/api/window/frames/index.md @@ -27,7 +27,6 @@ var frames = window.frames; // 或 // var frames = window.parent.frames; for (var i = 0; i < frames.length; i++) { // 在这对 frames 的一个 frame 做点什么 frames[i].document.body.style.background = "red"; - } ``` diff --git a/files/zh-cn/web/api/window/fullscreen/index.md b/files/zh-cn/web/api/window/fullscreen/index.md index 004c146b96ad72..c501c19172812c 100644 --- a/files/zh-cn/web/api/window/fullscreen/index.md +++ b/files/zh-cn/web/api/window/fullscreen/index.md @@ -20,6 +20,7 @@ isInFullScreen = windowRef.fullScreen; ## 返回值 - `isInFullScreen` + - : 一个布尔值。可能的值如下: - `true`: 窗口处于全屏模式下。 diff --git a/files/zh-cn/web/api/window/gamepadconnected_event/index.md b/files/zh-cn/web/api/window/gamepadconnected_event/index.md index ff4c78ab6914c3..62354f188ecbaf 100644 --- a/files/zh-cn/web/api/window/gamepadconnected_event/index.md +++ b/files/zh-cn/web/api/window/gamepadconnected_event/index.md @@ -22,23 +22,21 @@ slug: Web/API/Window/gamepadconnected_event ## 属性 -| Property | Type | Description | -| ----------------- | ------------------------------------ | --------------------------------------------------------- | -| `target` 只读 | {{domxref("DOMString")}} | 事件目标(DOM 树中的顶层,即 document.documentElement)。 | +| Property | Type | Description | +| ----------------- | -------------------------- | --------------------------------------------------------- | +| `target` 只读 | {{domxref("DOMString")}} | 事件目标(DOM 树中的顶层,即 document.documentElement)。 | | `type` 只读 | {{domxref("EventTarget")}} | 事件的类型。 | -| `bubbles` 只读 | {{jsxref("Boolean")}} | 事件是否正常冒泡。 | -| `cancelable` 只读 | {{jsxref("Boolean")}} | 事件是否可以取消。 | -| `gamepad` 只读 | {{domxref("Gamepad")}} | 单个游戏手柄属性,可用于访问关联游戏手柄的数据。 | +| `bubbles` 只读 | {{jsxref("Boolean")}} | 事件是否正常冒泡。 | +| `cancelable` 只读 | {{jsxref("Boolean")}} | 事件是否可以取消。 | +| `gamepad` 只读 | {{domxref("Gamepad")}} | 单个游戏手柄属性,可用于访问关联游戏手柄的数据。 | ## 示例 ```js // 请注意,在实现该 API 的浏览器中,该 API 仍为供应商前缀 -window.addEventListener("gamepadconnected", function( event ) { - - // 所有按钮和轴值均可通过以下方式访问 - event.gamepad; - +window.addEventListener("gamepadconnected", function (event) { + // 所有按钮和轴值均可通过以下方式访问 + event.gamepad; }); ``` diff --git a/files/zh-cn/web/api/window/gamepaddisconnected_event/index.md b/files/zh-cn/web/api/window/gamepaddisconnected_event/index.md index 4707a2883f1127..9587ec46c121f2 100644 --- a/files/zh-cn/web/api/window/gamepaddisconnected_event/index.md +++ b/files/zh-cn/web/api/window/gamepaddisconnected_event/index.md @@ -18,7 +18,7 @@ window.ongamepaddisconnected = function() { ... }; ## 示例 ```js -window.ongamepaddisconnected = function() { +window.ongamepaddisconnected = function () { // A gamepad has been disconnected }; ``` diff --git a/files/zh-cn/web/api/window/getcomputedstyle/index.md b/files/zh-cn/web/api/window/getcomputedstyle/index.md index 0293e41ae53537..58bcdc2ab14b74 100644 --- a/files/zh-cn/web/api/window/getcomputedstyle/index.md +++ b/files/zh-cn/web/api/window/getcomputedstyle/index.md @@ -58,20 +58,17 @@ let style = window.getComputedStyle(elem1, null); ``` ```js -function dumpComputedStyles(elem,prop) { - - let cs = window.getComputedStyle(elem,null); +function dumpComputedStyles(elem, prop) { + let cs = window.getComputedStyle(elem, null); if (prop) { - dump(" "+prop+" : "+cs.getPropertyValue(prop)+"\n"); + dump(" " + prop + " : " + cs.getPropertyValue(prop) + "\n"); return; } let len = cs.length; - for (var i=0;i - h3::after { - content: "rocks!"; - } + h3::after { + content: "rocks!"; + }

generated content

``` diff --git a/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.md b/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.md index 12c8b9f38a7d58..4cd0f54dec643b 100644 --- a/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.md +++ b/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.md @@ -57,18 +57,18 @@ The returned object is of the same type as the object returned by [`getComputedS ```html

generated content

``` diff --git a/files/zh-cn/web/api/window/getselection/index.md b/files/zh-cn/web/api/window/getselection/index.md index b6a911faa23dbd..7c8db071995d75 100644 --- a/files/zh-cn/web/api/window/getselection/index.md +++ b/files/zh-cn/web/api/window/getselection/index.md @@ -19,10 +19,10 @@ const selection = window.getSelection() ; ```js function foo() { - let selObj = window.getSelection(); - console.log(selObj); - let selRange = selObj.getRangeAt(0); - // 其他代码 + let selObj = window.getSelection(); + console.log(selObj); + let selRange = selObj.getRangeAt(0); + // 其他代码 } ``` diff --git a/files/zh-cn/web/api/window/hashchange_event/index.md b/files/zh-cn/web/api/window/hashchange_event/index.md index 30ae6464599f67..65ae4f97aa0969 100644 --- a/files/zh-cn/web/api/window/hashchange_event/index.md +++ b/files/zh-cn/web/api/window/hashchange_event/index.md @@ -1,5 +1,5 @@ --- -title: 'Window: hashchange event' +title: "Window: hashchange event" slug: Web/API/Window/hashchange_event --- @@ -35,16 +35,20 @@ slug: Web/API/Window/hashchange_event 你可以在 {{domxref("EventTarget/addEventListener", "addEventListener")}} 方法中使用 `hashchange` 事件: ```js -window.addEventListener('hashchange', function() { - console.log('The hash has changed!') -}, false); +window.addEventListener( + "hashchange", + function () { + console.log("The hash has changed!"); + }, + false, +); ``` 或使用 `onhashchange` 事件处理程序属性: ```js function locationHashChanged() { - if (location.hash === '#cool-feature') { + if (location.hash === "#cool-feature") { console.log("You're visiting a cool feature!"); } } diff --git a/files/zh-cn/web/api/window/history/index.md b/files/zh-cn/web/api/window/history/index.md index e3c45f5f89855b..033d725516526c 100644 --- a/files/zh-cn/web/api/window/history/index.md +++ b/files/zh-cn/web/api/window/history/index.md @@ -18,8 +18,8 @@ var historyObj = window.history; ## 示例 ```js -history.back(); // 等同于点击浏览器的回退按钮 -history.go(-1); //等同于 history.back(); +history.back(); // 等同于点击浏览器的回退按钮 +history.go(-1); //等同于 history.back(); ``` ## 附注 diff --git a/files/zh-cn/web/api/window/load_event/index.md b/files/zh-cn/web/api/window/load_event/index.md index 5b494c238bcb63..e8e73e6505c8bd 100644 --- a/files/zh-cn/web/api/window/load_event/index.md +++ b/files/zh-cn/web/api/window/load_event/index.md @@ -18,9 +18,9 @@ slug: Web/API/Window/load_event 在如 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 等方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('load', (event) => {}); +addEventListener("load", (event) => {}); -onload = (event) => { }; +onload = (event) => {}; ``` ## 事件类型 @@ -32,8 +32,8 @@ onload = (event) => { }; 当页面完全加载后在控制台打印一段信息: ```js -window.addEventListener('load', (event) => { - console.log('page is fully loaded'); +window.addEventListener("load", (event) => { + console.log("page is fully loaded"); }); ``` @@ -41,7 +41,7 @@ window.addEventListener('load', (event) => { ```js window.onload = (event) => { - console.log('page is fully loaded'); + console.log("page is fully loaded"); }; ``` @@ -56,7 +56,12 @@ window.onload = (event) => {
- +
``` @@ -81,7 +86,8 @@ body { resize: none; } -label, button { +label, +button { display: block; } @@ -93,25 +99,25 @@ label, button { #### JavaScript ```js -const log = document.querySelector('.event-log-contents'); -const reload = document.querySelector('#reload'); +const log = document.querySelector(".event-log-contents"); +const reload = document.querySelector("#reload"); -reload.addEventListener('click', () => { - log.textContent =''; +reload.addEventListener("click", () => { + log.textContent = ""; setTimeout(() => { - window.location.reload(true); + window.location.reload(true); }, 200); }); -window.addEventListener('load', (event) => { - log.textContent += 'load\n'; +window.addEventListener("load", (event) => { + log.textContent += "load\n"; }); -document.addEventListener('readystatechange', (event) => { +document.addEventListener("readystatechange", (event) => { log.textContent += `readystate: ${document.readyState}\n`; }); -document.addEventListener('DOMContentLoaded', (event) => { +document.addEventListener("DOMContentLoaded", (event) => { log.textContent += `DOMContentLoaded\n`; }); ``` diff --git a/files/zh-cn/web/api/window/localstorage/index.md b/files/zh-cn/web/api/window/localstorage/index.md index cbbf4507d0998e..df5756323a1d75 100644 --- a/files/zh-cn/web/api/window/localstorage/index.md +++ b/files/zh-cn/web/api/window/localstorage/index.md @@ -31,19 +31,19 @@ myStorage = localStorage; 下面的代码片段访问了当前域名下的本地 {{domxref("Storage")}} 对象,并通过 {{domxref("Storage.setItem()")}} 增加了一个数据项目。 ```js -localStorage.setItem('myCat', 'Tom'); +localStorage.setItem("myCat", "Tom"); ``` 该语法用于读取 `localStorage` 项,如下: ```js -let cat = localStorage.getItem('myCat'); +let cat = localStorage.getItem("myCat"); ``` 该语法用于移除 `localStorage` 项,如下: ```js -localStorage.removeItem('myCat'); +localStorage.removeItem("myCat"); ``` 该语法用于移除所有的 `localStorage` 项,如下: