-
Notifications
You must be signed in to change notification settings - Fork 232
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extract Canvas2D batch renderers to their own file
- Loading branch information
Showing
2 changed files
with
139 additions
and
72 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
// This file contains a collection of classes which make it easier to perform | ||
// batch rendering of Canvas2D primitives. The advantage of this over just doing | ||
// ctx.beginPath() ... ctx.rect(...) ... ctx.endPath() is that you can construct | ||
// several different batch renderers are the same time, then decide on their | ||
// paint order at the end. | ||
// | ||
// See FlamechartPanZoomView.renderOverlays for an example of how this is used. | ||
|
||
export interface TextArgs { | ||
text: string | ||
x: number | ||
y: number | ||
} | ||
|
||
export class BatchCanvasTextRenderer { | ||
private argsBatch: TextArgs[] = [] | ||
|
||
text(args: TextArgs) { | ||
this.argsBatch.push(args) | ||
} | ||
|
||
fill(ctx: CanvasRenderingContext2D, color: string) { | ||
if (this.argsBatch.length === 0) return | ||
ctx.fillStyle = color | ||
for (let args of this.argsBatch) { | ||
ctx.fillText(args.text, args.x, args.y) | ||
} | ||
this.argsBatch = [] | ||
} | ||
} | ||
|
||
export interface RectArgs { | ||
x: number | ||
y: number | ||
w: number | ||
h: number | ||
} | ||
|
||
export class BatchCanvasRectRenderer { | ||
private argsBatch: RectArgs[] = [] | ||
|
||
rect(args: RectArgs) { | ||
this.argsBatch.push(args) | ||
} | ||
|
||
private drawPath(ctx: CanvasRenderingContext2D) { | ||
ctx.beginPath() | ||
for (let args of this.argsBatch) { | ||
ctx.rect(args.x, args.y, args.w, args.h) | ||
} | ||
ctx.closePath() | ||
this.argsBatch = [] | ||
} | ||
|
||
fill(ctx: CanvasRenderingContext2D, color: string) { | ||
if (this.argsBatch.length === 0) return | ||
ctx.fillStyle = color | ||
this.drawPath(ctx) | ||
ctx.fill() | ||
} | ||
|
||
stroke(ctx: CanvasRenderingContext2D, color: string, lineWidth: number) { | ||
if (this.argsBatch.length === 0) return | ||
ctx.strokeStyle = color | ||
ctx.lineWidth = lineWidth | ||
this.drawPath(ctx) | ||
ctx.stroke() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters