From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/html/element/canvas/index.html | 164 +++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 files/zh-cn/web/html/element/canvas/index.html (limited to 'files/zh-cn/web/html/element/canvas/index.html') diff --git a/files/zh-cn/web/html/element/canvas/index.html b/files/zh-cn/web/html/element/canvas/index.html new file mode 100644 index 0000000000..8f9fd88ea9 --- /dev/null +++ b/files/zh-cn/web/html/element/canvas/index.html @@ -0,0 +1,164 @@ +--- +title: +slug: Web/HTML/Element/canvas +tags: + - Canvas + - HTML + - HTML5 + - Web +translation_of: Web/HTML/Element/canvas +--- +

<canvas>元素可被用来通过JavaScript(Canvas API 或 WebGL API)绘制图形及图形动画。

+ +

{{HTMLRef}}

+ +

属性

+ +

本元素支持 全局属性.

+ +
+
{{htmlattrdef("height")}}
+
该元素占用空间的高度,以 CSS 像素(px)表示,默认为 150。
+
{{htmlattrdef("moz-opaque")}} {{non-standard_inline}} {{deprecated_inline}}
+
通过设置这个属性,来控制canvas元素是否半透明。如果你不想canvas元素被设置为半透明,使用这个元素将可以优化浏览器绘图性能。
+
{{htmlattrdef("width")}}
+
该元素占用空间的宽度,以 CSS 像素(px)表示,默认为 300。
+
+ +

注意事项

+ +

标签需要闭合

+ +

不同于 {{HTMLElement("img")}} 元素,  {{HTMLElement ("canvas")}}元素需要有闭合标签 (</canvas>).

+ +

设置画布(canvas)的大小

+ +

直接在html标签中设置width和height属性或者使用JavaScript来指定画布尺寸,这将改变一个画布的水平像素和垂直像素数,就像定义了一张图片的大小一样。

+ +

可以使用CSS的width和height以在渲染期间缩放图像以适应样式大小,就像<img>元素一样。如果您发现<canvas>元素中展示的内容变形,您可以通过<canvas>自带的height和width属性进行相关设置,而不要使用CSS。

+ +

最大的画布尺寸

+ +

画布的最大的尺寸取决于浏览器,下表的结论来自别处 (e.g. Stack Overflow):

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
浏览器最大高度最大宽度最大面积
Chrome32,767 pixels32,767 pixels268,435,456 pixels (i.e., 16,384 x 16,384)
Firefox32,767 pixels32,767 pixels472,907,776 pixels (i.e., 22,528 x 20,992)
Safari32,767 pixels32,767 pixels268,435,456 pixels (i.e., 16,384 x 16,384)
IE8,192 pixels8,192 pixels?
+ +

示例

+ +

HTML

+ +
<canvas id="canvas" width="300" height="300">
+  抱歉,您的浏览器不支持canvas元素
+  (这些内容将会在不支持<canvas>元素的浏览器或是禁用了JavaScript的浏览器内渲染并展现)
+</canvas>
+
+ +

JavaScript

+ +

使用{{domxref("HTMLCanvasElement.getContext()")}}获得一个绘图上下文并开始绘制

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.fillStyle = 'green';
+ctx.fillRect(10, 10, 100, 100);
+ +

结果

+ +

{{EmbedLiveSample('示例')}}

+ +

可访问性

+ +

<canvas> 元素本身只是一个位图,不提供任何绘制对象的信息。画布内容不像HTML那样具有语义并能暴露给可访问性工具。以下指南可以帮助您更方便地访问它。

+ + + +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'the-canvas-element.html#the-canvas- element', '<canvas>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'the-canvas-element.html#the-canvas- element', '<canvas>')}}{{Spec2('HTML5 W3C')}}初始定义
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.canvas")}}

+ +

参阅

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