-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
55 lines (47 loc) · 1.46 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* eslint-disable import/no-extraneous-dependencies */
const NodeCanvas = require("canvas");
const fs = require("fs");
const path = require("path");
const htmlStyle = require('html-style');
const out = fs.createWriteStream(path.join(__dirname, "./render.png"));
const HtmlCanvas = require("../../miniprogram_dist/index");
const demoHtml = fs.readFileSync(path.resolve(__dirname, '../demo.html'), {
encoding: 'utf8'
});
const demoCss = fs.readFileSync(path.resolve(__dirname, '../demo.css'), {
encoding: 'utf8'
});
const demo = htmlStyle(demoHtml, demoCss);
const canvasWidth = 350;
let nodeCanvas = NodeCanvas.createCanvas(canvasWidth, canvasWidth);
let ctx = nodeCanvas.getContext("2d");
const Node = HtmlCanvas.Node;
const Image = NodeCanvas.Image;
Node.prototype.loadImage = function (src) {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => {
resolve(img);
}
img.onerror = err => {
reject(err);
}
img.src = src;
})
}
const tree = Node.fromHtml(demo);
tree.setStyle('width', `${canvasWidth}px`)
tree
.layout(ctx)
.then(() => {
nodeCanvas = NodeCanvas.createCanvas(canvasWidth, tree.boxHeight().value());
ctx = nodeCanvas.getContext("2d");
const canvas = new HtmlCanvas.Canvas(ctx);
canvas.draw(tree);
const stream = nodeCanvas.createPNGStream()
stream.pipe(out)
out.on('finish', () => console.log('The png file was created.'))
})
.catch(e => {
console.error(e);
});