Canvas

Last updated: ... / Reads: 36 Edit

CanvasRenderingContext2D 对象是 HTML5 中 <canvas> 元素的绘图上下文对象,它提供了一组用于在 canvas 上进行 2D 图形绘制的方法和属性。通过获取这个上下文对象,你可以在 canvas 上进行绘制,包括绘制图形、文字、图像等。

以下是获取 CanvasRenderingContext2D 对象的方式:

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');

上述代码中,myCanvas 是你 HTML 中 <canvas> 元素。

绘制形状

通过 CanvasRenderingContext2D 对象,你可以使用多种方法来绘制不同的形状,包括矩形、圆形、路径等。以下是一些基本的形状绘制方法:

绘制矩形

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');

// 绘制填充矩形
context.fillStyle = 'blue';
context.fillRect(10, 10, 50, 50);

// 绘制边框矩形
context.strokeStyle = 'red';
context.lineWidth = 2;
context.strokeRect(70, 10, 50, 50);

绘制圆形

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');

// 绘制填充圆形
context.beginPath();
context.arc(150, 35, 25, 0, 2 * Math.PI);
context.fillStyle = 'green';
context.fill();

// 绘制边框圆形
context.beginPath();
context.arc(220, 35, 25, 0, 2 * Math.PI);
context.strokeStyle = 'purple';
context.lineWidth = 2;
context.stroke();

绘制路径

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');

// 绘制路径
context.beginPath();
context.moveTo(10, 100);
context.lineTo(50, 50);
context.lineTo(90, 100);
context.closePath();

// 填充路径
context.fillStyle = 'orange';
context.fill();

// 描边路径
context.strokeStyle = 'brown';
context.lineWidth = 2;
context.stroke();

这只是一些基本的例子,CanvasRenderingContext2D 提供了丰富的方法用于绘制各种形状和效果。你可以根据需要组合这些方法,创建出复杂的图形。

绘制文本

在 HTML5 中,你可以使用 CanvasRenderingContext2D 对象来绘制文本。以下是一个简单的例子:

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');

// 设置文本样式
context.font = '20px Arial';
context.fillStyle = 'black';

// 绘制填充文本
context.fillText('Hello, Canvas!', 10, 30);

// 绘制描边文本
context.strokeStyle = 'blue';
context.lineWidth = 2;
context.strokeText('Hello, Canvas!', 10, 60);

上述代码中,fillText 方法用于填充文本,而 strokeText 方法用于描边文本。你可以通过设置 font 属性来指定文本的字体样式,设置 fillStylestrokeStyle 属性来指定文本的填充颜色和描边颜色。

如果你需要在多行中绘制文本,可以使用 fillTextstrokeText 方法,并在每行之间调整 y 坐标。


Comments

Make a comment