面试题答案
一键面试设计思路
- 创建一个
CanvasDrawer
类,用于封装 Canvas 绘图操作。 - 在类中定义绘制不同图形(如圆形、三角形)的方法,每个方法接受特定的参数来定义图形的属性(如圆心坐标、半径、三角形顶点坐标等),并返回
void
类型,因为这些方法主要是进行绘图操作,不返回具体值。 - 定义一个
drawShape
方法,该方法接受一个图形类型参数(如'circle'
或'triangle'
)以及相应图形的参数,根据图形类型调用对应的绘制方法。
代码实现
class CanvasDrawer {
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D | null;
constructor(canvasId: string) {
this.canvas = document.getElementById(canvasId) as HTMLCanvasElement;
this.ctx = this.canvas.getContext('2d');
if (!this.ctx) {
throw new Error('Could not get 2D context for the canvas');
}
}
// 绘制圆形方法
drawCircle(x: number, y: number, radius: number, color: string): void {
if (!this.ctx) return;
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, 2 * Math.PI);
this.ctx.fillStyle = color;
this.ctx.fill();
}
// 绘制三角形方法
drawTriangle(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, color: string): void {
if (!this.ctx) return;
this.ctx.beginPath();
this.ctx.moveTo(x1, y1);
this.ctx.lineTo(x2, y2);
this.ctx.lineTo(x3, y3);
this.ctx.closePath();
this.ctx.fillStyle = color;
this.ctx.fill();
}
// 根据图形类型调用相应绘制方法
drawShape(shapeType: 'circle' | 'triangle', ...args: any[]): void {
if (shapeType === 'circle') {
const [x, y, radius, color] = args;
this.drawCircle(x, y, radius, color);
} else if (shapeType === 'triangle') {
const [x1, y1, x2, y2, x3, y3, color] = args;
this.drawTriangle(x1, y1, x2, y2, x3, y3, color);
}
}
}
你可以这样使用这个类:
// 创建 CanvasDrawer 实例
const drawer = new CanvasDrawer('myCanvas');
// 绘制圆形
drawer.drawShape('circle', 100, 100, 50, 'blue');
// 绘制三角形
drawer.drawShape('triangle', 150, 50, 200, 150, 100, 150,'red');
在上述代码中,CanvasDrawer
类通过构造函数获取 Canvas 元素及其 2D 上下文。drawCircle
和 drawTriangle
方法分别用于绘制圆形和三角形。drawShape
方法根据传入的图形类型和参数调用相应的绘制方法。最后通过创建 CanvasDrawer
实例并调用 drawShape
方法来绘制不同的图形。确保 HTML 中有一个 id 为 myCanvas
的 Canvas 元素。