HTMLCanvasElement:width 属性
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
HTMLCanvasElement.width
属性是一个正整数(integer
),表示以 CSS 像素为单位解析的 <canvas>
元素的 width
HTML 属性。当未指定该属性,或者设置为无效值(例如负数)时,将使用默认值 300
。
当设置 width
属性时,绘图缓冲区总是会被重置为空白状态——这对于所有上下文类型都适用,即使高度被设置为相同的值也是如此。如果需要恢复之前的内容,可以通过 CanvasRenderingContext2D.getImageData()
保存,并通过 CanvasRenderingContext2D.putImageData()
进行恢复。
这是控制画布大小的两个属性之一,另一个属性是 HTMLCanvasElement.height
。
值
一个数字。
示例
给定以下 <canvas>
元素:
html
<canvas id="canvas" width="300" height="300"></canvas>
你可以通过以下代码获取画布的宽度:
js
const canvas = document.getElementById("canvas");
console.log(canvas.width); // 300
规范
Specification |
---|
HTML # dom-canvas-height |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
width |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
参见
HTMLCanvasElement
:用于定义HTMLCanvasElement.width
属性的接口HTMLCanvasElement.height
:用于控制画布大小的另一个属性HTMLEmbedElement.width
HTMLIFrameElement.width
HTMLImageElement.width
HTMLObjectElement.width
HTMLSourceElement.width
HTMLVideoElement.width