HTML Academy · 课时

设置画布与二维上下文

创建 canvas 元素并获取二维渲染上下文

第 1 / 4 课13 个步骤

设置画布与二维上下文 是 CoddyKit 上的免费 HTML Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 HTML Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 HTML Academy 课程共包含 4 节课。

canvas 元素

<canvas> 元素是浏览器中的可绘制位图表面:

<canvas id="myCanvas" width="800" height="400">
  <!-- Fallback for browsers without canvas support -->
  <p>Your browser does not support HTML5 Canvas.</p>
</canvas>

宽度和高度属性

始终通过 HTML 属性设置 canvas 尺寸,而不要使用 CSS:

<!-- CORRECT: set intrinsic size via attributes -->
<canvas width="800" height="400"></canvas>

<!-- WRONG: CSS changes display size but not canvas resolution -->
<canvas style="width: 800px; height: 400px;"></canvas>
<!-- This stretches a default 300x150 canvas to 800x400
     Result: blurry graphics -->

获取二维上下文

获取二维渲染上下文以进行绘制:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// ctx is a CanvasRenderingContext2D object
// All drawing operations are methods on ctx

// Check browser support:
if (!canvas.getContext) {
  console.error('Canvas not supported');
}

坐标系

canvas 坐标系的起点位于左上角:

// (0, 0) = top-left corner
// (width, 0) = top-right
// (0, height) = bottom-left
// (width, height) = bottom-right

// For a 800x400 canvas:
// x increases left → right (0 to 800)
// y increases top → bottom (0 to 400)
//
// Example: draw at center:
ctx.fillRect(400, 200, 10, 10);  // centered dot

canvas 状态

canvas 具有可保存和恢复的绘图状态:

ctx.save();       // push current state onto a stack

// Change state:
ctx.fillStyle = 'red';
ctx.globalAlpha = 0.5;

// Draw with modified state...
ctx.fillRect(100, 100, 200, 200);

ctx.restore();    // pop state: back to pre-save settings

清除 canvas

在重新绘制之前清除整个 canvas(用于动画):

// Clear entire canvas:
ctx.clearRect(0, 0, canvas.width, canvas.height);

// Or with a background color:
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);

fillStyle 和 strokeStyle

设置填充和描边操作的颜色:

ctx.fillStyle = 'blue';                    // CSS color name
ctx.fillStyle = '#ff6600';                 // hex color
ctx.fillStyle = 'rgb(255, 100, 0)';       // rgb
ctx.fillStyle = 'rgba(255, 100, 0, 0.5)'; // rgba with alpha
ctx.fillStyle = gradient;                  // gradient object
ctx.fillStyle = pattern;                   // pattern object

ctx.strokeStyle = '#333333';               // border color

lineWidth 和其他样式属性

描边和线条样式属性:

ctx.lineWidth = 4;           // stroke width in pixels
ctx.lineCap = 'round';       // butt | round | square
ctx.lineJoin = 'round';      // miter | round | bevel
ctx.setLineDash([5, 3]);     // dashed line: 5px dash, 3px gap
ctx.globalAlpha = 0.8;       // transparency for all drawing
ctx.globalCompositeOperation = 'multiply'; // blend modes

自适应 HiDPI canvas

修复 Retina/HiDPI 显示屏上的 canvas 模糊问题:

function setupHiDPI(canvas, width, height) {
  const dpr = window.devicePixelRatio || 1;
  canvas.width = width * dpr;
  canvas.height = height * dpr;
  canvas.style.width = width + 'px';
  canvas.style.height = height + 'px';
  const ctx = canvas.getContext('2d');
  ctx.scale(dpr, dpr);  // scale all drawing
  return ctx;
}

Canvas 与 SVG

何时选择 canvas,何时选择 SVG:

  • Canvas——位图,逐像素处理,适合游戏、大型数据可视化和图像处理
  • SVG——矢量图,可缩放,适合徽标、图标、带交互元素的图表以及无障碍访问

Canvas 无障碍访问

Canvas 没有内置的无障碍支持,需要手动添加:

<canvas
  id="chart"
  width="800"
  height="400"
  aria-label="Bar chart showing Q1-Q4 revenue growth"
  role="img"
>
  <!-- Fallback for non-canvas browsers and screen readers -->
  <table><!-- accessible data table --></table>
</canvas>

快速检查

获取 canvas 绘图上下文的正确方式是什么?

回顾:Canvas 设置

Canvas 设置的核心要点:

  • 通过 HTML 属性设置宽度和高度,而不要使用 CSS
  • canvas.getContext('2d')——获取绘图上下文
  • 原点位于左上角(0,0);x 向右,y 向下
  • ctx.save() / ctx.restore()——基于堆栈的状态管理
  • 根据 devicePixelRatio 进行缩放,以实现清晰的 Retina 渲染
免费开始

用 AI 导师学习 HTML — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
40
课程
159

常见问题解答

「设置画布与二维上下文」课时是免费的吗?

是的 — 「设置画布与二维上下文」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 HTML Academy 课程的其余内容,请升级到 CoddyKit PRO。 HTML Academy 课程共包含 4 节课。

「设置画布与二维上下文」这节课中我会学到什么?

创建 canvas 元素并获取二维渲染上下文 你通过在浏览器中直接运行的动手代码来练习 HTML Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 HTML Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 HTML Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「设置画布与二维上下文」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 HTML Academy 课中编写并运行代码吗?

能。每节 HTML Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设置画布与二维上下文
  2. 绘制矩形和路径
  3. 在画布上绘制文本和图像
  4. 使用 requestAnimationFrame 制作动画
← 返回 HTML Academy