html5 canvas绘制圆形、方形矩形、线段、图片等各种图形(面向对象版本)
// 定义一个绘图类
class Graphics {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
}
// 绘制圆形
drawCircle(x, y, radius, fillColor) {
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
this.ctx.fillStyle = fillColor;
this.ctx.fill();
}
// 绘制矩形
drawRect(x, y, width, height, fillColor) {
this.ctx.fillStyle = fillColor;
this.ctx.fillRect(x, y, width, height);
}
// 绘制线段
drawLine(startX, startY, endX, endY, lineColor, lineWidth) {
this.ctx.beginPath();
this.ctx.moveTo(startX, startY);
this.ctx.lineTo(endX, endY);
this.ctx.strokeStyle = lineColor;
this.ctx.lineWidth = lineWidth;
this.ctx.stroke();
}
// 绘制图片
drawImage(image, x, y, width, height) {
this.ctx.drawImage(image, x, y, width, height);
}
}
// 使用示例
const canvas = document.getElementById('myCanvas');
const graphics = new Graphics(canvas);
graphics.drawCircle(75, 75, 50, 'green');
graphics.drawRect(12, 12, 100, 200, 'blue');
graphics.drawLine(0, 0, 200, 100, 'red', 5);
const image = new Image();
image.src = 'path_to_image.jpg';
image.onload = () => {
graphics.drawImage(image, 50, 50, 100, 100);
};
这段代码定义了一个名为Graphics
的类,它封装了绘制图形的各种方法。通过实例化Graphics
类,并调用其方法,可以在指定的canvas
上绘制不同的图形。这种面向对象的方式使得代码结构清晰,易于管理和扩展。
评论已关闭