From 8233cb094b24186b37a77a8d5806c60ed1889c74 Mon Sep 17 00:00:00 2001 From: unanmed <1319491857@qq.com> Date: Wed, 4 Dec 2024 19:35:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Rect=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/render/item.ts | 7 +++++ src/core/render/preset/graphics.ts | 49 ++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/core/render/item.ts b/src/core/render/item.ts index 650e71e..1531085 100644 --- a/src/core/render/item.ts +++ b/src/core/render/item.ts @@ -247,6 +247,13 @@ export abstract class RenderItem /** 该渲染元素的子元素 */ children: Set> = new Set(); + get x() { + return this._transform.x; + } + get y() { + return this._transform.y; + } + /** 渲染缓存信息 */ protected cache: MotaOffscreenCanvas2D = new MotaOffscreenCanvas2D(); /** 是否需要更新缓存 */ diff --git a/src/core/render/preset/graphics.ts b/src/core/render/preset/graphics.ts index e17ec40..a1a5e60 100644 --- a/src/core/render/preset/graphics.ts +++ b/src/core/render/preset/graphics.ts @@ -74,10 +74,22 @@ export abstract class GraphicItemBase setLineOption(options: Partial) {} /** - * 设置绘制样式 + * 设置填充样式 * @param style 绘制样式 */ - setStyle(style: CanvasStyle) {} + setFillStyle(style: CanvasStyle) {} + + /** + * 设置描边样式 + * @param style 绘制样式 + */ + setStrokeStyle(style: CanvasStyle) {} + + /** + * 设置填充原则 + * @param rule 填充原则 + */ + setFillRule(rule: CanvasFillRule) {} /** * 设置绘制模式,是描边还是填充 @@ -85,6 +97,15 @@ export abstract class GraphicItemBase */ setMode(mode: GraphicMode) {} + /** + * 设置画布的渲染状态,在实际渲染前调用 + * @param canvas 要设置的画布 + */ + protected setCanvasState(canvas: MotaOffscreenCanvas2D) { + const ctx = canvas.ctx; + ctx.fillStyle = this.fill; // 示例,后面的都按这个写,不需要save restore,写完把这个注释删了 + } + patchProp( key: string, prevValue: any, @@ -102,7 +123,29 @@ export class Rect extends GraphicItemBase { protected render( canvas: MotaOffscreenCanvas2D, transform: Transform - ): void {} + ): void { + const ctx = canvas.ctx; + this.setCanvasState(canvas); + ctx.beginPath(); + ctx.rect(this.x, this.y, this.width, this.height); + + switch (this.mode) { + case GraphicMode.Fill: + ctx.fill(this.fillRule); + break; + case GraphicMode.Stroke: + ctx.stroke(); + break; + case GraphicMode.FillAndStroke: + ctx.fill(this.fillRule); + ctx.stroke(); + break; + case GraphicMode.StrokeAndFill: + ctx.stroke(); + ctx.fill(this.fillRule); + break; + } + } patchProp( key: string,