Skip to content

Commit

Permalink
automatically refresh after tileset loads
Browse files Browse the repository at this point in the history
  • Loading branch information
danprince committed Mar 20, 2022
1 parent fd3741f commit 1abd53f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 13 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ term.color = "red";
term.background = "#0000FF";
term.put(0, 0, 0x10);
term.write(10, 10, "Hello world");

// Wait for the tileset to load before rendering
term.tileset.onload = () => term.refresh();
term.refresh();

// Make the canvas visible
document.body.append(term.canvas);
Expand Down
7 changes: 2 additions & 5 deletions example/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,8 @@ onmousemove = e => {
m = t.screenToGrid(e.clientX, e.clientY);
}

function start() {
drawBackground();
loop();
}
drawBackground();
loop();

function drawBackground() {
t.layer = 1;
Expand Down Expand Up @@ -59,6 +57,5 @@ function loop() {
t.refresh();
}

t.tileset.onload = start;
t.canvas.style.background = "black";
document.body.append(t.canvas);
17 changes: 12 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import defaultFontUrl from "./font.png";
import defaultTilesetUrl from "./font.png";

type TileSet = HTMLImageElement | HTMLCanvasElement;

Expand Down Expand Up @@ -112,12 +112,16 @@ export class Terminal {
constructor(
width: number,
height: number,
url: string = defaultFontUrl,
url: string = defaultTilesetUrl,
cellWidth = 6,
cellHeight = 6,
) {
let tileset = new Image();
tileset.src = url;

// Draw anything that was buffered before the tileset loaded
tileset.addEventListener("load", () => this.refresh());

let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d")!;
canvas.width = width * cellWidth;
Expand Down Expand Up @@ -246,7 +250,10 @@ export class Terminal {
* Renders the terminal to the canvas.
*/
refresh() {
let { canvas, ctx, tileset: font, width, cellWidth, cellHeight } = this;
// Can't render unless the tileset has loaded
if (this.tileset.width === 0) return;

let { canvas, ctx, tileset, width, cellWidth, cellHeight } = this;
ctx.clearRect(0, 0, canvas.width, canvas.height);

for (let layer of this.layers) {
Expand All @@ -261,8 +268,8 @@ export class Terminal {
let bg = buffer[i++];
let offsetX = buffer[i++];
let offsetY = buffer[i++];
let img: HTMLImageElement | HTMLCanvasElement = font;
let cols = font.width / cellWidth;
let img: HTMLImageElement | HTMLCanvasElement = tileset;
let cols = tileset.width / cellWidth;
let cw = cellWidth;
let ch = cellHeight;
let sx = (code % cols) * cw;
Expand Down

0 comments on commit 1abd53f

Please sign in to comment.