-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathto-data-url.js
57 lines (44 loc) · 1.46 KB
/
to-data-url.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
56
57
const PIXI = require("./pixi");
const { createCanvas, loadImage, Image } = require("canvas");
// creates new PIXI.Application({ --> view <-- })
module.exports.createView = function createView(width, height) {
const view = createCanvas(width, height, "image");
view.addEventListener = () => null;
view.style = {};
return view;
};
// creates sprite from source
module.exports.createSprite = async function createSprite(source) {
const image = await loadImage(source);
const canvas = createCanvas(image.width, image.height, "image");
const ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
const baseTexture = PIXI.BaseTexture.fromBuffer(
canvas.toBuffer(),
canvas.width,
canvas.height,
);
const texture = new PIXI.Texture(baseTexture);
const sprite = new PIXI.Sprite(texture);
return sprite;
};
// saves view to data url
module.exports.toDataURL = function toDataURL(app) {
const ctx = app.view.getContext("2d");
// iterate over children
app.stage.children.forEach((child) => {
if (child instanceof PIXI.Sprite) {
const buffer = child.texture.baseTexture.resource.data;
const image = new Image(child.width, child.height);
image.src = buffer;
// and draw them on canvas manually
ctx.drawImage(
image,
child.x - child.anchor.x * child.width,
child.y - child.anchor.y * child.height,
);
}
});
const base64 = app.view.toDataURL("image/png");
return base64;
};