在 HTML5 中,<canvas> 元素用于通过 JavaScript 绘制图形。ctx.canvas.width 和 ctx.canvas.height 是 Canvas 2D 上下文(CanvasRenderingContext2D)中获取画布实际像素宽高的属性。
基本概念
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 获取画布的像素宽度和高度
console.log(ctx.canvas.width); // 等同于 canvas.width
console.log(ctx.canvas.height); // 等同于 canvas.height
重要区别:CSS尺寸 vs Canvas尺寸
Canvas 有两个不同的尺寸概念:
| 属性 | 含义 | 影响 |
|---|---|---|
canvas.width / canvas.height |
画布像素尺寸(实际绘图区域大小) | 决定绘图的分辨率和可绘制范围 |
CSS width / height |
显示尺寸(元素在页面中的视觉大小) | 只影响缩放显示,不影响绘图分辨率 |
示例说明
<canvas id="myCanvas" width="300" height="200"></canvas>
<style>
#myCanvas {
width: 600px; /* CSS放大显示 */
height: 400px;
}
</style>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
console.log(canvas.width); // 300(像素尺寸)
console.log(canvas.height); // 200(像素尺寸)
// 注意:实际显示被CSS拉伸到600x400,但绘图仍按300x200进行
</script>
常见用途
自适应窗口大小
function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }高清屏适配(Retina)
const dpr = window.devicePixelRatio || 1; canvas.width = displayWidth * dpr; canvas.height = displayHeight * dpr; ctx.scale(dpr, dpr);清空画布
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);获取中心点坐标
const centerX = ctx.canvas.width / 2; const centerY = ctx.canvas.height / 2;
注意事项
ctx.canvas返回的是当前上下文关联的<canvas>元素引用- 修改
canvas.width或canvas.height会自动清空画布内容 - 这两个属性始终返回整数像素值(不包含单位”px”)
简单来说,ctx.canvas.width 和 ctx.canvas.height 就是告诉你画布有多少个像素点可以用来画画,而不是它在屏幕上看起来有多大。
