Goal: Understand how to transform html and css to image.
I follow this in typescript. Let's build a browser engine! Part 1: Getting started
NOTE: this is the way of 2014. This is html4.01, css2, etc.
I want to understand step by step. I want to see incrementally. Some program creates canvas with color, then I can paint this to stdout.
// node_modules/.bin/ts-node example/canvas-color.ts | display
import * as Jimp from "jimp";
import { Canvas } from "../src/painting";
import { Color } from "../src/css";
const white = new Color(255, 255, 255, 255);
const black = new Color(0, 0, 0, 255);
const canvas = new Canvas(
new Array(5 * 10).fill(white).concat(new Array(5 * 10).fill(black)),
10,
10
);
Jimp.create(canvas.width, canvas.height)
.then((value: Jimp) => {
let buffer = value.bitmap.data;
for (let i = 0; i < canvas.pixels.length; i++) {
buffer[i * 4] = canvas.pixels[i].r;
buffer[i * 4 + 1] = canvas.pixels[i].g;
buffer[i * 4 + 2] = canvas.pixels[i].b;
buffer[i * 4 + 3] = canvas.pixels[i].a;
}
return value.getBufferAsync(Jimp.MIME_PNG);
})
.then((value: Buffer) => {
process.stdout.write(value);
})
.catch((error: Error) => {
console.error(error);
});
This is my first step. if I can do this, then I'll get clear conscience about my success :)
import { Color } from "../src/css";
test("a", () => {
expect(new Color(0, 0, 0, 255).a).toEqual(255);
});
export class Color {
r: number;
g: number;
b: number;
a: number;
constructor(r: number, g: number, b: number, a: number) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
}
import { Canvas } from "../src/painting";
import { Color } from "../src/css";
test("canvas pixels length", () => {
const canvas = Canvas.Create(2, 3);
expect(canvas.pixels.length).toEqual(6);
});
test("canvas is filled by white", () => {
const canvas = Canvas.Create(2, 3);
const white = new Color(255, 255, 255, 255);
expect(canvas.pixels).toEqual([white, white, white, white, white, white]);
});
import { Color } from "./css";
export class Canvas {
pixels: Color[];
width: number;
height: number;
constructor(pixels: Color[], width: number, height: number) {
this.pixels = pixels;
this.width = width;
this.height = height;
}
static Create(width: number, height: number): Canvas {
const white = new Color(255, 255, 255, 255);
return new Canvas(new Array(width * height).fill(white), width, height);
}
}
Finally, I got this, yeah!
references
- Let's build a browser engine! Part 1: Getting started
- mbrubeck/robinson
- sanemat/js-toy-engine
- sanemat/ts-toy-engine
series
- Let's build browser engine! in typescript vol0 Toy browser engine
- Let's build browser engine! in typescript vol1 Canvas with Color
- Let's build browser engine! in typescript vol2 Display Command
- Let's build browser engine! in typescript vol3 Layout Box, Dimensions
- Let's build browser engine! in typescript vol4 Layout Tree to Display List
Top comments (0)