# HTML5核心特性-第5章-5.3-Canvas绘图基础
## 一、学习目标
- 掌握Canvas元素的基本使用方法,包括获取绘图上下文
- 熟悉2D绘图API的常用方法(矩形、路径、文本绘制)
- 能够实现简单的图形绘制和动态效果
## 二、概念讲解
Canvas是HTML5引入的绘图元素,通过JavaScript可以在其上面绘制2D图形、动画、图表等。它提供了一个矩形区域,开发者可以通过调用Canvas API来控制像素级的绘制操作。与SVG不同,Canvas是基于像素的位图绘图,放大后可能失真,但性能更优,适合复杂动画和游戏开发。
**核心概念**:
- **Canvas元素**:通过``标签定义绘图区域,需指定`width`和`height`属性(默认300×150像素)
- **绘图上下文**:通过`getContext('2d')`获取2D绘图环境,所有绘图操作都通过上下文对象执行
- **坐标系**:默认以左上角为原点(0,0),x轴向右递增,y轴向下递增
## 三、语法参考
### 3.1 Canvas元素基本结构
```html
// 获取Canvas元素
const canvas = document.getElementById('myCanvas');
// 获取2D绘图上下文
const ctx = canvas.getContext('2d');
// 开始绘图操作...
```
### 3.2 常用2D绘图API
| 方法/属性 | 描述 | 示例 |
|-------------------------|---------------------------------------|-------------------------------------------|
| `fillRect(x,y,w,h)` | 绘制填充矩形 | `ctx.fillRect(50,50,200,100)` |
| `strokeRect(x,y,w,h)` | 绘制边框矩形 | `ctx.strokeRect(50,50,200,100)` |
| `beginPath()` | 开始新路径 | `ctx.beginPath()` |
| `arc(x,y,r,start,end)` | 绘制圆弧/圆形(弧度制) | `ctx.arc(250,150,80,0,Math.PI*2)` |
| `fill()` | 填充当前路径 | `ctx.fill()` |
| `stroke()` | 描边当前路径 | `ctx.stroke()` |
| `fillText(text,x,y)` | 绘制填充文本 | `ctx.fillText('Hello Canvas', 50, 50)` |
| `font` | 设置文本字体和大小 | `ctx.font = "24px Arial"` |
| `fillStyle` | 设置填充颜色/渐变/图案 | `ctx.fillStyle = "#4CAF50"` |
| `strokeStyle` | 设置描边颜色/渐变/图案 | `ctx.strokeStyle = "red"` |
## 四、实战示例
### 示例1:绘制基本图形组合
```html
const canvas = document.getElementById('shapeCanvas');
const ctx = canvas.getContext('2d');
// 1. 绘制填充矩形(红色)
ctx.fillStyle = '#ff4444';
ctx.fillRect(50, 50, 100, 80);
// 2. 绘制边框矩形(蓝色,线宽3px)
ctx.strokeStyle = '#33b5e5';
ctx.lineWidth = 3;
ctx.strokeRect(200, 50, 100, 80);
// 3. 绘制圆形(绿色填充,黄色描边)
ctx.beginPath();
ctx.arc(150, 200, 40, 0, Math.PI * 2); // 圆心(150,200),半径40
ctx.fillStyle = '#00C851';
ctx.fill();
ctx.strokeStyle = '#ffeb3b';
ctx.lineWidth = 2;
ctx.stroke();
// 4. 绘制文本(黑色,20px Arial)
ctx.font = '20px Arial';
ctx.fillStyle = '#333';
ctx.fillText('基本图形绘制', 120, 30);
```
**效果说明**:该示例在Canvas上绘制了红色填充矩形、蓝色边框矩形、绿色填充圆形(黄色描边)和标题文本,展示了基本绘图API的组合使用。
### 示例2:路径绘制与动画效果
```html
const canvas = document.getElementById('animateCanvas');
const ctx = canvas.getContext('2d');
let x = 50; // 圆形初始x坐标
let speed = 2; // 移动速度
function draw() {
// 1. 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 2. 绘制移动的圆形
ctx.beginPath();
ctx.arc(x, 150, 30, 0, Math.PI * 2);
ctx.fillStyle = '#aa66cc';
ctx.fill();
// 3. 更新位置(边界检测)
x += speed;
if (x > canvas.width - 30 || x < 30) {
speed = -speed; // 反向移动
}
// 4. 循环动画
requestAnimationFrame(draw);
}
// 启动动画
draw();
```
**效果说明**:该示例实现了一个在Canvas中左右移动的紫色圆形,通过`requestAnimationFrame`实现平滑动画,每次绘制前清除画布,避免图形重叠。
## 五、注意事项
1. **Canvas大小设置**:
- 必须通过`width`/`height`属性设置Canvas尺寸,而非CSS样式(CSS会拉伸画布导致失真)。
- 示例:``(正确) vs ``(错误)。
2. **像素精度问题**:
- 绘制线条时若出现模糊,可将坐标设置为半像素(如`strokeRect(10.5,10.5,80,40)`),避免抗锯齿导致的模糊。
3. **性能优化**:
- 复杂动画时使用`requestAnimationFrame`而非`setInterval`,确保浏览器刷新率同步。
- 频繁绘制的场景可使用离屏Canvas缓存静态内容。
4. **兼容性**:
- 所有现代浏览器(Chrome/Firefox/Safari/Edge)均支持Canvas,但IE9及以下不支持,需提供替代内容:
```html
您的浏览器不支持Canvas,请升级浏览器。
```
## 六、自测题
1. Canvas元素默认的宽高是多少?如何正确设置其尺寸?
2. 以下代码绘制的图形是什么?`ctx.beginPath(); ctx.arc(100,100,50,0,Math.PI); ctx.fill();`
3. 如何在Canvas中实现一个逐渐变色的矩形?(提示:使用线性渐变)
4. 简述`fillRect()`和`strokeRect()`的区别,以及它们与`rect()`+`fill()`组合的区别。
## 七、扩展阅读
- [MDN Canvas API文档](https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API)
- [Canvas高级教程:像素操作与图像合成](https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas)
- [Canvas性能优化指南](https://developers.google.com/web/updates/2018/08/offscreen-canvas)
HTML5核心特性-第5章-5.3-Canvas绘图基础
2 分钟阅读
308 字
如果文章对您有帮助,欢迎支持作者继续创作