/** * 格子仿画绘制服务 * 合并了基础绘制和内容绘制逻辑 */ import { BaseDrawService } from '../../../service/baseDraw'; import { GridCell, GridConfig } from '../types/gridTypes'; /** * 格子仿画数据 */ export interface GridDrawingData { config: GridConfig; cells: GridCell[]; name?: string; } /** * 格子仿画绘制服务 */ class GridDraw extends BaseDrawService { gridData: GridDrawingData | null = null; constructor( canvas: Canvas, ctx: RenderingContext, options?: Record, ) { super(canvas, ctx, options); } /** * 绘制格子仿画内容 */ async draw(gridData: GridDrawingData) { if (!gridData || !gridData.cells) { return; } this.setPrintConfig(); this.gridData = gridData; this.clear(); this.setPaper(); // 绘制Header if (this.headerType !== 'minimal') { await this.drawHeader(); } else { this.drawMiniHeader(); } // 绘制内容区域(网格和填充) this.drawDivider(); await this.drawGridContent({ canvas: this.canvas, ctx: this.ctx, gridData: this.gridData, canvasWidth: this.canvasWidth, startY: this.currentY, }); } /** * 绘制网格内容 */ private async drawGridContent(params: { canvas: WechatMiniprogram.Canvas; ctx: RenderingContext; gridData: GridDrawingData; canvasWidth: number; startY: number; }): Promise { const { ctx, gridData, canvasWidth, startY } = params; const { config, cells } = gridData; const { rows, cols } = config; // 计算网格尺寸 const margin = 40; // 左右边距 const availableWidth = canvasWidth - margin * 2; const cellSize = Math.floor(availableWidth / cols); const gridWidth = cellSize * cols; const gridHeight = cellSize * rows; // 计算网格起始位置(居中) const gridStartX = margin + (availableWidth - gridWidth) / 2; const gridStartY = startY + 30; // 顶部间距 // 绘制网格线 ctx.strokeStyle = config.gridLineColor || '#000000'; ctx.lineWidth = config.gridLineWidth || 1; ctx.setLineDash([]); // 实线 // 绘制垂直线 for (let i = 0; i <= cols; i++) { const x = gridStartX + i * cellSize; ctx.beginPath(); ctx.moveTo(x, gridStartY); ctx.lineTo(x, gridStartY + gridHeight); ctx.stroke(); } // 绘制水平线 for (let i = 0; i <= rows; i++) { const y = gridStartY + i * cellSize; ctx.beginPath(); ctx.moveTo(gridStartX, y); ctx.lineTo(gridStartX + gridWidth, y); ctx.stroke(); } // 绘制填充的格子 for (const cell of cells) { if (cell.x >= 0 && cell.x < cols && cell.y >= 0 && cell.y < rows) { const x = gridStartX + cell.x * cellSize; const y = gridStartY + cell.y * cellSize; // 填充颜色 ctx.fillStyle = cell.color; ctx.fillRect(x + 1, y + 1, cellSize - 2, cellSize - 2); } } } } export default GridDraw;