blob: cfcdf23fad5869ce6408221a1f178f92ba3f8e4d [file] [log] [blame]
Kevin Lubick53eabf62018-12-10 12:41:26 -05001CanvasKit.MakeCanvas = function(width, height) {
2 // TODO(kjlubick) do fonts the "correct" way
3 CanvasKit.initFonts();
4 var surf = CanvasKit.MakeSurface(width, height);
5 if (surf) {
6 return new HTMLCanvas(surf);
7 }
8 return null;
9}
10
11function HTMLCanvas(skSurface) {
12 this._surface = skSurface;
13 this._context = new CanvasRenderingContext2D(skSurface.getCanvas());
14 this._imgs = [];
15
16 // Data is either an ArrayBuffer, a TypedArray, or a Node Buffer
17 this.decodeImage = function(data) {
18 var img = CanvasKit.MakeImageFromEncoded(data);
19 if (!img) {
20 throw 'Invalid input';
21 }
22 this._imgs.push(img);
23 return img;
24 }
25
26 // A normal <canvas> requires that clients call getContext
27 this.getContext = function(type) {
28 if (type === '2d') {
29 return this._context;
30 }
31 return null;
32 }
33
34 this.toDataURL = function(codec, quality) {
35 // TODO(kjlubick): maybe support other codecs (webp?)
36 // For now, just to png and jpeg
37 this._surface.flush();
38
39 var img = this._surface.makeImageSnapshot();
40 if (!img) {
41 SkDebug('no snapshot');
42 return;
43 }
44 var codec = codec || 'image/png';
45 var format = CanvasKit.ImageFormat.PNG;
46 if (codec === 'image/jpeg') {
47 format = CanvasKit.ImageFormat.JPEG;
48 }
49 var quality = quality || 0.92;
50 var skimg = img.encodeToData(format, quality);
51 if (!skimg) {
52 SkDebug('encoding failure');
53 return
54 }
55 var imgBytes = CanvasKit.getSkDataBytes(skimg);
56 return 'data:' + codec + ';base64,' + toBase64String(imgBytes);
57 }
58
59 this.dispose = function() {
60 this._context._dispose();
61 this._imgs.forEach(function(i) {
62 i.delete();
63 });
64 this._surface.dispose();
65 }
66}