--- title: HTMLCanvasElement.width slug: Web/API/HTMLCanvasElement/width translation_of: Web/API/HTMLCanvasElement/width ---
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
Specification | Status | Comment |
---|---|---|
{{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. |