From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../api/htmlcanvaselement/getcontext/index.html | 161 ++++++++++++++++ .../web/api/htmlcanvaselement/height/index.html | 123 +++++++++++++ files/zh-cn/web/api/htmlcanvaselement/index.html | 92 ++++++++++ .../web/api/htmlcanvaselement/mozopaque/index.html | 53 ++++++ .../web/api/htmlcanvaselement/toblob/index.html | 204 +++++++++++++++++++++ .../web/api/htmlcanvaselement/todataurl/index.html | 155 ++++++++++++++++ .../transfercontroltooffscreen/index.html | 65 +++++++ .../webglcontextlost_event/index.html | 82 +++++++++ .../web/api/htmlcanvaselement/width/index.html | 123 +++++++++++++ .../index.html" | 122 ++++++++++++ 10 files changed, 1180 insertions(+) create mode 100644 files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/height/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/toblob/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html create mode 100644 files/zh-cn/web/api/htmlcanvaselement/width/index.html create mode 100644 "files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" (limited to 'files/zh-cn/web/api/htmlcanvaselement') diff --git a/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html b/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..07c0e6820c --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,161 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - API + - Canvas +translation_of: Web/API/HTMLCanvasElement/getContext +--- +
{{APIRef("Canvas API")}}
+ +

HTMLCanvasElement.getContext() 方法返回{{jsxref("canvas")}} 的上下文,如果上下文没有定义则返回 {{jsxref("null")}} .

+ +

在同一个canvas上以相同的 contextType 多次调用此方法只会返回同一个上下文。

+ +

语法

+ +
var ctx = canvas.getContext(contextType);
+var ctx = canvas.getContext(contextType, contextAttributes);
+ +

参数

+ +
+
上下文类型(contextType)
+
是一个指示使用何种上下文的 {{domxref("DOMString")}} 。可能的值是: +
    +
  • "2d", 建立一个 {{domxref("CanvasRenderingContext2D")}} 二维渲染上下文。
  • +
  • "webgl" (或"experimental-webgl") 这将创建一个 {{domxref("WebGLRenderingContext")}} 三维渲染上下文对象。只在实现WebGL 版本1(OpenGL ES 2.0)的浏览器上可用。
  • +
  • "webgl2" (或 "experimental-webgl2") 这将创建一个 {{domxref("WebGL2RenderingContext")}} 三维渲染上下文对象。只在实现 WebGL 版本2 (OpenGL ES 3.0)的浏览器上可用。{{experimental_inline}}
  • +
  • "bitmaprenderer" 这将创建一个只提供将canvas内容替换为指定{{domxref("ImageBitmap")}}功能的{{domxref("ImageBitmapRenderingContext")}}  。
  • +
+ +
+

注意: 标识符 "experimental-webgl" 或 "experimental-webgl2" 用于新 WebGL的实现。 这些实现还没有达到测试套件一致性或图形驱动程序平台局势尚不稳定。Khronos Group 集团认证WebGL 实现在某些一致性规则

+
+
+
上下文属性(contextAttributes)
+
+

你可以在创建渲染上下文的时候设置多个属性,例如:

+ +
canvas.getContext("webgl",
+                 { antialias: false,
+                   depth: false });
+ 2d 上下文属性: + +
    +
  • alpha: {{jsxref("boolean")}}值表明{{jsxref("canvas")}}包含一个{{jsxref("alpha")}}通道. 如果设置为{{jsxref("false")}}, 浏览器将认为{{jsxref("canvas")}}背景总是不透明的, 这样可以加速绘制透明的内容和图片.
  • +
  • {{non-standard_inline}} (Gecko only) willReadFrequently: {{jsxref("boolean")}}值表明是否有重复读取计划。经常使用{{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}},这将迫使软件使用2D {{jsxref("canvas")}} 并 节省内存(而不是硬件加速)。这个方案适用于存在属性 gfx.canvas.willReadFrequently的环境。并设置为{{jsxref("true")}} (缺省情况下,只有B2G / Firefox OS).
  • +
  • {{non-standard_inline}} (Blink only) storage: {{jsxref("string")}} 这样表示使用哪种方式存储(默认为:持久("persistent")).
  • +
+ WebGL上下文属性: + +
    +
  • +

    alpha: {{jsxref("boolean")}}值表明{{jsxref("canvas")}}包含一个{{jsxref("alpha")}}缓冲区。

    +
  • +
  • +

    antialias: {{jsxref("boolean")}}值表明是否开启抗锯齿。

    +
  • +
  • +

    depth: {{jsxref("boolean")}}值表明绘制缓冲区包含一个深度至少为16位的缓冲区。

    +
  • +
  • +

    failIfMajorPerformanceCaveat: 表明在一个系统性能低的环境是否创建该上下文的{{jsxref("boolean")}}值。

    +
  • +
  • +

    powerPreference: 指示浏览器在运行WebGL上下文时使用相应的GPU电源配置。 可能值如下:

    + +
      +
    • +

      "default":自动选择,默认值。

      +
    • +
    • +

      "high-performance": 高性能模式。

      +
    • +
    • +

      "low-power": 节能模式。

      +
    • +
    +
  • +
  • +

    premultipliedAlpha: 表明排版引擎讲假设绘制缓冲区包含预混合alpha通道的{{jsxref("boolean")}}值。

    +
  • +
  • +

    preserveDrawingBuffer: 如果这个值为{{jsxref("true")}}缓冲区将不会被清除,会保存下来,直到被清除或被使用者覆盖。

    +
  • +
  • +

    stencil: 表明绘制缓冲区包含一个深度至少为8位的模版缓冲区{{jsxref("boolean")}}值。

    +
  • +
+
+
+ +

返回值

+ +

{{domxref("RenderingContext")}} 返回值是下列之一:

+ + + +

如果 contextType 不是上述之一,返回{{jsxref("null")}}.

+ +

例子

+ +

定义 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

通过如下代码可以获取 {{jsxref("canvas")}}2d 上下文:

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+console.log(ctx); // CanvasRenderingContext2D { ... }
+
+ +

现在你已经获取到了2D 画布的渲染上下文({{domxref("CanvasRenderingContext2D")}}),可以使用它画你想画的了.

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLCanvasElement.getContext")}}

+ +

另请参阅

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/height/index.html b/files/zh-cn/web/api/htmlcanvaselement/height/index.html new file mode 100644 index 0000000000..a479e87d7e --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/height/index.html @@ -0,0 +1,123 @@ +--- +title: HTMLCanvasElement.height +slug: Web/API/HTMLCanvasElement/height +translation_of: Web/API/HTMLCanvasElement/height +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.height 属性是一个正整数 ,使用了{{HTMLElement("canvas")}} 元素的HTML 属性{{htmlattrxref("height", "canvas")}}来反映该元素高度的 CSS 像素值。当该属性没有被定义,或被定义为一个无效值(如负值)时, 将使用150作为它的默认值。

+ +

控制canvas元素大小的属性有两个,这是其中一个,还有一个是{{domxref("HTMLCanvasElement.width")}}。

+ +

语法

+ +
var pxl = canvas.height;
+canvas.height = pxl;
+
+ +

示例

+ +

给出这样一个{{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

可以通过以下代码获得这个canvas元素的高度:

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.height); // 300
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(4) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("1.9.2") }}{{ CompatIE(9) }}{{ CompatOpera(9) }}{{ CompatSafari(3.1) }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.9.2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

其他

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/index.html b/files/zh-cn/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..0a6e76ff7d --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/index.html @@ -0,0 +1,92 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +translation_of: Web/API/HTMLCanvasElement +--- +

{{APIRef("Canvas API")}}

+ +

HTMLCanvasElement接口提供用于操纵{{HtmlElement("canvas")}}元素的布局和表示的属性和方法。 HTMLCanvasElement接口还继承了{{domxref("HTMLElement")}}接口的属性和方法。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

属性

+ +

从其父项{{domxref("HTMLElement")}}继承属性。

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
是一个正整数,反映了{{HTMLElement("canvas")}} 元素的{{htmlattrxref("height", "canvas")}} HTML属性,以CSS像素表示。 如果未指定属性,或者将其设置为无效值(例如负数),则使用默认值150。
+
{{domxref("HTMLCanvasElement.width")}}
+
是一个正整数,反映了{{HTMLElement("canvas")}} 元素的{{htmlattrxref("width", "canvas")}} HTML属性,以CSS像素表示。 如果未指定属性,或者将其设置为无效值(例如负数),则使用默认值300。
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}} {{deprecated_inline}}
+
是反映 {{HTMLElement("canvas")}}元素的{{htmlattrxref("moz-opaque", "canvas")}} 属性的{{jsxref("Boolean")}}。 它让画布知道半透明性是否会成为一个因素。 如果画布知道没有透明感,则可以优化绘画性能。 仅基于Mozilla的浏览器支持此功能, 可以使用标准化的{{domxref("HTMLCanvasElement.getContext()", "canvas.getContext('2d', { alpha: false })")}} 代替。
+
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
+
是最初为空的函数。 Web内容可以将其设置为JavaScript函数,该函数将在打印页面时重新绘制画布时调用。 调用时,回调将传递一个实现了MozCanvasPrintState接口的“ printState”对象。 回调可以从printState对象获取要绘制的上下文,然后必须在完成时在其上调用done() 。 mozPrintCallback 的目的是在所使用打印机的分辨率下获得较高分辨率的画布渲染。 请参阅此博客文章
+
+ +

方法

+ +

从其父项{{domxref("HTMLElement")}}继承方法。

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
返回{{domxref("CanvasCaptureMediaStream")}} ,它是对画布表面的实时视频捕获。
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
返回画布上的绘图上下文;如果不支持上下文ID,则返回null。 绘图上下文可让您在画布上绘图。 调用getContext传入"2d" 可以返回一个{{domxref("CanvasRenderingContext2D")}}对象,也可以传入"webgl"(或"experimental-webgl")返回一个{{domxref("WebGLRenderingContext")}} 对象。 此上下文仅在实现WebGL的浏览器上可用。
+
{{domxref("HTMLCanvasElement.toDataURL()")}}
+
返回一个数据URL,该URL包含由类型参数指定的格式的图像(默认为png)。 返回的图像分辨率为96dpi。
+
{{domxref("HTMLCanvasElement.toBlob()")}}
+
创建一个{{domxref("Blob")}} 对象,表示canvas中包含的图像; 该文件可以由用户代理决定是否缓存在磁盘上或存储在内存中。
+
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
+
将控制权转移到主线程或辅助线程上的 {{domxref("OffscreenCanvas")}}对象。
+
+

过时的方法

+
+
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{obsolete_inline}}
+
返回代表画布中包含的图像的{{domxref("File")}} 对象; 该文件是基于内存的文件,具有指定的名称。 如果未指定类型,则图像类型为image / png。
+
+ +

事件

+ +

使用addEventListener()监听这些事件。

+ +
+
webglcontextcreationerror
+
如果用户代理无法创建WebGLRenderingContext 或WebGL2RenderingContext 上下文,则触发该事件。
+
webglcontextlost
+
如果用户代理检测到与WebGLRenderingContext 或WebGL2RenderingContext 对象关联的绘图缓冲区已丢失,则触发此事件。
+
webglcontextrestored
+
如果用户代理为WebGLRenderingContext 或WebGL2RenderingContext 对象恢复绘图缓冲区,则触发该事件。
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlcanvaselement", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}}Primary definition of HTMLCanvasElement.
{{SpecName('Media Capture DOM Elements', '#html-canvas-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}Adds the method captureStream().
+ +

浏览器支持

+ + + +

{{Compat("api.HTMLCanvasElement")}}

+ +
diff --git a/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html b/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html new file mode 100644 index 0000000000..b82b5718db --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.html @@ -0,0 +1,53 @@ +--- +title: HTMLCanvasElement.mozOpaque +slug: Web/API/HTMLCanvasElement/mozOpaque +tags: + - API + - Canvas + - HTMLCanvasElement +translation_of: Web/API/HTMLCanvasElement/mozOpaque +--- +
{{APIRef("Canvas API")}}{{non-standard_header}}
+ +

非标准的 HTMLCanvasElement.mozOpaque 是一种 {{jsxref("Boolean")}} 的数据反映了{{HTMLElement("canvas")}}元素的{htmlattrxref("moz-opaque", "canvas")} HTML属性。它能够让画布(canvas)将半透明作为一个参考因素。如果画布知道没有半透明因素,作画的性能可以优化。

+ +

当使用{{domxref("HTMLCanvasElement.getContext()")}}创建绘图上下文时,该api将被标准化为将alpha选项设置为false。应该避免使用mozOpaque。Firefox将在未来停止支持它。

+ +

语法

+ +
var opaque = canvas.mozOpaque;
+canvas.mozOpaque = true;
+
+ +

示例

+ +

有如下{{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas" width="300" height="300" moz-opaque></canvas>
+
+ +

你可以获取或设置 mozOpaque 属性. 例如,当mimeType == 'image/jpeg'或类似值时,可以将其属性值设置为true,以在不需要半透明度的情况下提高应用程序的性能。

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.mozOpaque); // true
+// 停用该方法
+canvas.mozOpaque = false;
+
+ +

规范

+ +

不属于任何标准。

+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLCanvasElement.mozOpaque")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/toblob/index.html b/files/zh-cn/web/api/htmlcanvaselement/toblob/index.html new file mode 100644 index 0000000000..d9388defd9 --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/toblob/index.html @@ -0,0 +1,204 @@ +--- +title: HTMLCanvasElement.toBlob() +slug: Web/API/HTMLCanvasElement/toBlob +translation_of: Web/API/HTMLCanvasElement/toBlob +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.toBlob() 方法创造{{domxref("Blob")}}对象,用以展示canvas上的图片;这个图片文件可以被缓存或保存到本地,由用户代理端自行决定。如不特别指明,图片的类型默认为 image/png,分辨率为96dpi。

+ +

第三个参数用于针对image/jpeg格式的图片进行输出图片的质量设置。

+ +

语法

+ +
canvas.toBlob(callback, type, encoderOptions);
+
+ +

参数

+ +
+
callback
+
回调函数,可获得一个单独的{{domxref("Blob")}}对象参数。
+
type {{optional_inline}}
+
{{domxref("DOMString")}}类型,指定图片格式,默认格式为image/png
+
encoderOptions {{optional_inline}}
+
{{jsxref("Number")}}类型,值在0与1之间,当请求图片格式为image/jpeg或者image/webp时用来指定图片展示质量。如果这个参数的值不在指定类型与范围之内,则使用默认值,其余参数将被忽略。
+
+ +

返回值

+ +

无。

+ +

异常

+ +
+
SecurityError
+
canvas“被污染”的情况下不能使用此方法
+
+ +

示例

+ +

将canvas图像转换为文件

+ +

当一个内容画到canvas上时,我们可以将它生成任何一个格式支持的图片文件。比如,下面的代码段获得了id为“canvas”的{{HTMLElement("canvas")}}元素中的图像,复制成一个PNG图,在文档中加入一个新的{{HTMLElement("img")}}元素,这个{{HTMLElement("img")}}元素的源图就是使用canvas创建的那个图像。 

+ +
var canvas = document.getElementById("canvas");
+
+canvas.toBlob(function(blob) {
+  var newImg = document.createElement("img"),
+      url = URL.createObjectURL(blob);
+
+  newImg.onload = function() {
+    // no longer need to read the blob so it's revoked
+    URL.revokeObjectURL(url);
+  };
+
+  newImg.src = url;
+  document.body.appendChild(newImg);
+});
+
+ +

注意,我们这里创建的是PNG图片;如果在toBlob()传入第二个参数,就可以指定图片格式。例如,生成JPEG格式的图片:

+ +
 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality
+ +
+

将canvas转换为ico(仅限Mozilla)

+ +

使用-moz-parse来将canvas转换为ico。Windows XP不支持将PNG转为ico,因此转为bmp作为代替。设置下载属性,生成下载链接。下载属性的值将被用来作为文件名。

+ +
var canvas = document.getElementById("canvas");
+var d = canvas.width;
+ctx = canvas.getContext("2d");
+ctx.beginPath();
+ctx.moveTo(d / 2, 0);
+ctx.lineTo(d, d);
+ctx.lineTo(0, d);
+ctx.closePath();
+ctx.fillStyle = "yellow";
+ctx.fill();
+
+function blobCallback(iconName) {
+  return function(b) {
+    var a = document.createElement("a");
+    a.textContent = "Download";
+    document.body.appendChild(a);
+    a.style.display = "block";
+    a.download = iconName + ".ico";
+    a.href = window.URL.createObjectURL(b);
+  }
+}
+canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
+              '-moz-parse-options:format=bmp;bpp=32');
+
+ +

Save toBlob to disk with OS.File (chrome/add-on context only)

+ +
+

This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code as OS APIs are not present on web sites.

+
+ +
var canvas = document.getElementById("canvas");
+var d = canvas.width;
+ctx = canvas.getContext("2d");
+ctx.beginPath();
+ctx.moveTo(d / 2, 0);
+ctx.lineTo(d, d);
+ctx.lineTo(0, d);
+ctx.closePath();
+ctx.fillStyle = "yellow";
+ctx.fill();
+
+function blobCallback(iconName) {
+  return function(b) {
+    var r = new FileReader();
+    r.onloadend = function () {
+    // r.result contains the ArrayBuffer.
+    Cu.import('resource://gre/modules/osfile.jsm');
+    var writePath = OS.Path.join(OS.Constants.Path.desktopDir,
+                                 iconName + '.ico');
+    var promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result),
+                                      {tmpPath:writePath + '.tmp'});
+    promise.then(
+      function() {
+        console.log('successfully wrote file');
+      },
+      function() {
+        console.log('failure writing file')
+      }
+    );
+  };
+  r.readAsArrayBuffer(b);
+  }
+}
+
+canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon',
+              '-moz-parse-options:format=bmp;bpp=32');
+ +

Polyfill

+ +

A low performance polyfill based on toDataURL.

+ +
if (!HTMLCanvasElement.prototype.toBlob) {
+ Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
+  value: function (callback, type, quality) {
+
+    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
+        len = binStr.length,
+        arr = new Uint8Array(len);
+
+    for (var i=0; i<len; i++ ) {
+     arr[i] = binStr.charCodeAt(i);
+    }
+
+    callback( new Blob( [arr], {type: type || 'image/png'} ) );
+  }
+ });
+}
+
+ +

文档

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5.1')}}No change
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-toblob", "HTMLCanvasElement.toBlob")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.HTMLCanvasElement.toBlob")}}

+ +

扩展阅读

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html b/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..724c67025f --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,155 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.toDataURL() 方法返回一个包含图片展示的 data URI 。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为96dpi。

+ + + +

语法

+ +
canvas.toDataURL(type, encoderOptions);
+
+ +

参数

+ +
+
type {{optional_inline}}
+
图片格式,默认为 image/png
+
encoderOptions {{optional_inline}}
+
在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。
+
+ +

返回值

+ +

包含 data URI 的{{domxref("DOMString")}}。

+ +

示例

+ +

有如下{{HTMLElement("canvas")}}元素

+ +
<canvas id="canvas" width="5" height="5"></canvas>
+
+ +

可以用这样的方式获取一个 data-URL

+ +
var canvas = document.getElementById("canvas");
+var dataURL = canvas.toDataURL();
+console.log(dataURL);
+// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
+// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
+
+ +

设置jpegs图片的质量

+ +
var fullQuality = canvas.toDataURL("image/jpeg", 1.0);
+// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"
+var mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
+var lowQuality = canvas.toDataURL("image/jpeg", 0.1);
+
+ +

示例:动态更改图片

+ +

可以使用鼠标事件来动态改变图片(这个例子中改变图片灰度)。

+ +

HTML

+ +
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
+ +

JavaScript

+ +
window.addEventListener("load", removeColors);
+
+function showColorImg() {
+  this.style.display = "none";
+  this.nextSibling.style.display = "inline";
+}
+
+function showGrayImg() {
+  this.previousSibling.style.display = "inline";
+  this.style.display = "none";
+}
+
+function removeColors() {
+  var aImages = document.getElementsByClassName("grayscale"),
+      nImgsLen = aImages.length,
+      oCanvas = document.createElement("canvas"),
+      oCtx = oCanvas.getContext("2d");
+  for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
+    oColorImg = aImages[nImgId];
+    nWidth = oColorImg.offsetWidth;
+    nHeight = oColorImg.offsetHeight;
+    oCanvas.width = nWidth;
+    oCanvas.height = nHeight;
+    oCtx.drawImage(oColorImg, 0, 0);
+    oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
+    aPix = oImgData.data;
+    nPixLen = aPix.length;
+    for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
+      aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
+    }
+    oCtx.putImageData(oImgData, 0, 0);
+    oGrayImg = new Image();
+    oGrayImg.src = oCanvas.toDataURL();
+    oGrayImg.onmouseover = showColorImg;
+    oColorImg.onmouseout = showGrayImg;
+    oCtx.clearRect(0, 0, nWidth, nHeight);
+    oColorImg.style.display = "none";
+    oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
+  }
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLCanvasElement.toDataURL")}}

+ +
+ +

参考

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html b/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html new file mode 100644 index 0000000000..6320ad324e --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.html @@ -0,0 +1,65 @@ +--- +title: HTMLCanvasElement.transferControlToOffscreen() +slug: Web/API/HTMLCanvasElement/transferControlToOffscreen +tags: + - Canvas + - Web图形技术 + - 离屏Canvas +translation_of: Web/API/HTMLCanvasElement/transferControlToOffscreen +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

方法 HTMLCanvasElement.transferControlToOffscreen() 将控制转移到一个在主线程或者web worker的 {{domxref("OffscreenCanvas")}} 对象上。

+ +

用法

+ +
OffscreenCanvas HTMLCanvasElement.transferControlToOffscreen()
+ +

返回值

+ +

一个 {{domxref("OffscreenCanvas")}} 对象。

+ +

样例

+ +
var htmlCanvas = document.createElement('canvas');
+var offscreen = htmlCanvas.transferControlToOffscreen();
+var gl = offscreen.getContext('webgl');
+
+// ... some drawing using the gl context ...
+
+// Push frames back to the original HTMLCanvasElement
+gl.commit();
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "canvas.html#dom-canvas-transfercontroltooffscreen", "HTMLCanvasElement.transferControlToOffscreen()")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.HTMLCanvasElement.transferControlToOffscreen")}}

+
+ +

查阅

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html b/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html new file mode 100644 index 0000000000..bd8c206ab8 --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.html @@ -0,0 +1,82 @@ +--- +title: 'HTMLCanvasElement: webglcontextlost event' +slug: Web/API/HTMLCanvasElement/webglcontextlost_event +translation_of: Web/API/HTMLCanvasElement/webglcontextlost_event +--- +
{{APIRef}}
+ +
+ +
+

如果浏览器检测到与 {{domxref("WebGLRenderingContext")}}对象关联的图形缓冲区已丢失,则会触发WebGL API 中的webglcontextlost 事件.

+
+ + + + + + + + + + + + + + + + + + + + +
冒泡Yes
可取消Yes
继承{{domxref("WebGLContextEvent")}}
事件处理程序属性none
+ +

例子

+ +

在 {{domxref("WEBGL_lose_context")}} 扩展的帮助下,您可以模拟 webglcontextlost 事件:

+ +
const canvas = document.getElementById('canvas');
+const gl = canvas.getContext('webgl');
+
+canvas.addEventListener('webglcontextlost', (event) => {
+  console.log(event);
+});
+
+//WEBGL_lose_context是webgl是属于 WebGLAPI 的一个扩展API,它提供一组方法用来模拟一个 WebGLRenderingContext 上下文的丢失和恢复。
+gl.getExtension('WEBGL_lose_context').loseContext();
+
+// "webglcontextlost" event is logged.
+ +

标准

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', '#5.15.2', 'webglcontextlost')}}{{Spec2('WebGL')}}Initial definition.
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.HTMLCanvasElement.webglcontextlost_event")}}

+
+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/htmlcanvaselement/width/index.html b/files/zh-cn/web/api/htmlcanvaselement/width/index.html new file mode 100644 index 0000000000..2384c0eb2d --- /dev/null +++ b/files/zh-cn/web/api/htmlcanvaselement/width/index.html @@ -0,0 +1,123 @@ +--- +title: HTMLCanvasElement.width +slug: Web/API/HTMLCanvasElement/width +translation_of: Web/API/HTMLCanvasElement/width +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.width 属性是一个对应 {{HTMLElement("canvas")}} 元素 CSS 像素 {{htmlattrxref("width", "canvas")}} 的正整数. 当这个属性没有指定时, 或者被赋予一个不合法的值, 比如一个负值, 默认使用 300.

+ +

这是其中之一,另一个是 {{domxref("HTMLCanvasElement.height")}}, 它们控制了 canvas 的大小尺寸.

+ +

语法

+ +
var pxl = canvas.width;
+canvas.width = pxl;
+
+ +

示例

+ +

有这样一个 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

你能够通过下面的代码得到 canvas 的宽度:

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.width); // 300
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-width", "HTMLCanvasElement.width")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-width", "HTMLCanvasElement.width")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-width", "HTMLCanvasElement.width")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(4) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("1.9.2") }}{{ CompatIE(9) }}{{ CompatOpera(9) }}{{ CompatSafari(3.1) }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.9.2") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

查看更多

+ + diff --git "a/files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" "b/files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" new file mode 100644 index 0000000000..999485b6f6 --- /dev/null +++ "b/files/zh-cn/web/api/htmlcanvaselement/\346\215\225\350\216\267\346\265\201/index.html" @@ -0,0 +1,122 @@ +--- +title: HTMLCanvasElement.captureStream() +slug: Web/API/HTMLCanvasElement/捕获流 +translation_of: Web/API/HTMLCanvasElement/captureStream +--- +
{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}
+ +

HTMLCanvasElement.captureStream() 方法返回的 {{domxref("CanvasCaptureMediaStream")}} 是一个实时视频捕获的画布。

+ +

语法

+ +
MediaStream = canvas.captureStream(frameRate);
+
+ +

参数

+ +
+
frameRate 可选
+
设置双精准度浮点值为每个帧的捕获速率。如果未设置,则每次画布更改时都会捕获一个新帧。如果设置为0,则会捕获单个帧。
+
+ +

返回值

+ +

对一个 {{domxref("MediaStream")}} 对象的引用.

+ +

例子

+ +
//获取所需要截取媒体流的canvas element
+var canvasElt = document.querySelector('canvas');
+
+//截取到媒体流
+var stream = canvasElt.captureStream(25); // 25 FPS
+
+//使用媒体流
+// E.g.使用RTCPeerConnection来传输给其它的电脑
+// 下面的pc是其他地方创建的一个RTCPeerConnection
+pc.addStream(stream);
+
+ +

产品规格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#widl-HTMLCanvasElement-captureStream-CanvasCaptureMediaStream-double-frameRate', 'HTMLCanvasElement.captureStream()')}}{{Spec2('Media Capture DOM Elements')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(51.0)}}{{CompatGeckoDesktop(43)}}[1]{{CompatNo}}{{CompatOpera(36.0)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(51.0)}}{{CompatChrome(51.0)}}{{CompatGeckoMobile(43)}}{{CompatNo}}{{CompatOpera(38)}}{{CompatUnknown}}
+
+ +

[1] 在Firefox 41和42中,此功能默认是禁用的; 将首选项 canvas.capturestream.enabled 设置 true 。

+ +

看看其他

+ + -- cgit v1.2.3-54-g00ecf