blob: 6f118e526421c31a33e80f48f863db84241e6a06 [file] [log] [blame]
Kevin Lubick53eabf62018-12-10 12:41:26 -05001CanvasKit.MakeCanvas = function(width, height) {
Kevin Lubick53eabf62018-12-10 12:41:26 -05002 var surf = CanvasKit.MakeSurface(width, height);
3 if (surf) {
4 return new HTMLCanvas(surf);
5 }
6 return null;
7}
8
9function HTMLCanvas(skSurface) {
10 this._surface = skSurface;
11 this._context = new CanvasRenderingContext2D(skSurface.getCanvas());
Kevin Lubick8e4a3312018-12-14 15:03:41 -050012 this._toCleanup = [];
13 this._fontmgr = CanvasKit.SkFontMgr.RefDefault();
Kevin Lubick53eabf62018-12-10 12:41:26 -050014
15 // Data is either an ArrayBuffer, a TypedArray, or a Node Buffer
16 this.decodeImage = function(data) {
17 var img = CanvasKit.MakeImageFromEncoded(data);
18 if (!img) {
19 throw 'Invalid input';
20 }
Kevin Lubick8e4a3312018-12-14 15:03:41 -050021 this._toCleanup.push(img);
Kevin Lubick53eabf62018-12-10 12:41:26 -050022 return img;
23 }
24
Kevin Lubick8e4a3312018-12-14 15:03:41 -050025 this.loadFont = function(buffer, descriptors) {
26 var newFont = this._fontmgr.MakeTypefaceFromData(buffer);
27 if (!newFont) {
28 SkDebug('font could not be processed', descriptors);
29 return null;
30 }
31 this._toCleanup.push(newFont);
32 addToFontCache(newFont, descriptors);
33 }
34
Kevin Lubick53eabf62018-12-10 12:41:26 -050035 // A normal <canvas> requires that clients call getContext
36 this.getContext = function(type) {
37 if (type === '2d') {
38 return this._context;
39 }
40 return null;
41 }
42
43 this.toDataURL = function(codec, quality) {
44 // TODO(kjlubick): maybe support other codecs (webp?)
45 // For now, just to png and jpeg
46 this._surface.flush();
47
48 var img = this._surface.makeImageSnapshot();
49 if (!img) {
50 SkDebug('no snapshot');
51 return;
52 }
53 var codec = codec || 'image/png';
54 var format = CanvasKit.ImageFormat.PNG;
55 if (codec === 'image/jpeg') {
56 format = CanvasKit.ImageFormat.JPEG;
57 }
58 var quality = quality || 0.92;
59 var skimg = img.encodeToData(format, quality);
60 if (!skimg) {
61 SkDebug('encoding failure');
62 return
63 }
64 var imgBytes = CanvasKit.getSkDataBytes(skimg);
65 return 'data:' + codec + ';base64,' + toBase64String(imgBytes);
66 }
67
68 this.dispose = function() {
69 this._context._dispose();
Kevin Lubick8e4a3312018-12-14 15:03:41 -050070 this._toCleanup.forEach(function(i) {
Kevin Lubick53eabf62018-12-10 12:41:26 -050071 i.delete();
72 });
73 this._surface.dispose();
74 }
75}