canvas

canvas

HTML5 <canvas> 元素是一个强大的绘图工具,允许开发者在网页上绘制图形、图像、动画等。以下是 <canvas> 的常用方法和属性的详细介绍。

1. 基本概念

<canvas> 是一个矩形区域,可以通过 JavaScript 的 CanvasRenderingContext2D 接口进行绘图操作。以下是基本的 HTML 和 JavaScript 初始化代码:

HTML

1
2
3
<canvas id="myCanvas" width="500" height="500">
您的浏览器不支持 Canvas。
</canvas>

JavaScript

1
2
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); // 获取 2D 渲染上下文

2. 常用属性

<canvas> 元素本身和 CanvasRenderingContext2D 对象都有一些重要的属性。

<canvas> 元素属性

  • widthheight:定义画布的宽度和高度(以像素为单位)。
    1
    <canvas width="500" height="500"></canvas>
  • getContext:获取绘图上下文(如 2dwebgl)。
    1
    const ctx = canvas.getContext('2d');

CanvasRenderingContext2D 属性

  • fillStyle:设置填充颜色或渐变。
    1
    2
    ctx.fillStyle = 'red';
    ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
  • strokeStyle:设置描边颜色或渐变。
    1
    ctx.strokeStyle = 'blue';
  • lineWidth:设置线条宽度。
    1
    ctx.lineWidth = 5;
  • font:设置文本字体。
    1
    ctx.font = '20px Arial';
  • textAligntextBaseline:设置文本对齐方式。
    1
    2
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
  • globalAlpha:设置全局透明度(范围为 0 到 1)。
    1
    ctx.globalAlpha = 0.5;
  • globalCompositeOperation:设置图形的合成方式(如 source-overdestination-over 等)。
    1
    ctx.globalCompositeOperation = 'xor';

3. 常用方法

CanvasRenderingContext2D 提供了丰富的绘图方法,可以绘制形状、路径、图像等。

绘制矩形

  • fillRect(x, y, width, height):绘制填充矩形。
    1
    2
    ctx.fillStyle = 'green';
    ctx.fillRect(10, 10, 100, 100);
  • strokeRect(x, y, width, height):绘制描边矩形。
    1
    2
    ctx.strokeStyle = 'black';
    ctx.strokeRect(10, 10, 100, 100);
  • clearRect(x, y, width, height):清除指定区域。
    1
    ctx.clearRect(10, 10, 100, 100);

绘制路径

  • beginPath():开始新的路径。
  • closePath():闭合路径。
  • moveTo(x, y):移动到指定点。
  • lineTo(x, y):绘制直线到指定点。
  • arc(x, y, radius, startAngle, endAngle, anticlockwise):绘制圆形或圆弧。
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y):绘制贝塞尔曲线。
  • quadraticCurveTo(cpx, cpy, x, y):绘制二次贝塞尔曲线。
  • fill():填充路径。
  • stroke():描边路径。
    示例:
1
2
3
4
5
6
7
8
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 150);
ctx.arc(150, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.strokeStyle = 'black';
ctx.stroke();

绘制文本

  • fillText(text, x, y):绘制填充文本。
    1
    ctx.fillText('Hello, Canvas!', 10, 50);
  • strokeText(text, x, y):绘制描边文本。
    1
    ctx.strokeText('Hello, Canvas!', 10, 50);

绘制图像

  • drawImage(image, x, y):将图像绘制到画布上。
    1
    2
    3
    4
    5
    const img = new Image();
    img.src = 'image.jpg';
    img.onload = () => {
    ctx.drawImage(img, 10, 10);
    };

转换和变换

  • translate(x, y):平移画布。
    1
    ctx.translate(100, 100);
  • rotate(angle):旋转画布。
    1
    ctx.rotate(Math.PI / 4); // 旋转45度
  • scale(x, y):缩放画布。
    1
    ctx.scale(2, 2); // 放大2倍
  • save()restore():保存和恢复画布状态。
    1
    2
    3
    ctx.save();
    ctx.translate(100, 100);
    ctx.restore();

4. 事件交互

<canvas> 元素支持鼠标和触摸事件,可以实现交互功能。

示例:绘制鼠标轨迹

1
2
3
4
5
6
7
8
9
10
11
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
ctx.fillRect(x, y, 5, 5);
});
</script>

5. 动画

通过 requestAnimationFrame 方法可以实现动画效果。

示例:移动的矩形

1
2
3
4
5
6
7
8
9
10
11
12
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = 0;
let y = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
ctx.fillRect(x, y, 50, 50); // 绘制矩形
x += 1; // 更新位置
y += 1;
requestAnimationFrame(animate); // 递归调用
}
animate();

6. 注意事项

  1. 性能优化:尽量减少 clearRect 和重绘操作。
  2. 分辨率适配:在高分辨率设备上,可能需要调整 canvas 的宽高以匹配显示效果。
  3. 兼容性<canvas> 在现代浏览器中广泛支持,但在旧版本浏览器中可能需要备用方案。
    通过这些方法和属性,你可以实现丰富的图形绘制和交互功能,满足大多数网页绘图需求。