blob: de9794f43f8e0c636138a46e4b15c60ba81a1d3a [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 Lubicka40f8322018-12-17 16:01:36 -050035 this.makePath2D = function(path) {
36 var p2d = new Path2D(path);
37 this._toCleanup.push(p2d._getPath());
38 return p2d;
39 }
40
Kevin Lubick53eabf62018-12-10 12:41:26 -050041 // A normal <canvas> requires that clients call getContext
42 this.getContext = function(type) {
43 if (type === '2d') {
44 return this._context;
45 }
46 return null;
47 }
48
49 this.toDataURL = function(codec, quality) {
50 // TODO(kjlubick): maybe support other codecs (webp?)
51 // For now, just to png and jpeg
52 this._surface.flush();
53
54 var img = this._surface.makeImageSnapshot();
55 if (!img) {
56 SkDebug('no snapshot');
57 return;
58 }
59 var codec = codec || 'image/png';
60 var format = CanvasKit.ImageFormat.PNG;
61 if (codec === 'image/jpeg') {
62 format = CanvasKit.ImageFormat.JPEG;
63 }
64 var quality = quality || 0.92;
65 var skimg = img.encodeToData(format, quality);
66 if (!skimg) {
67 SkDebug('encoding failure');
68 return
69 }
70 var imgBytes = CanvasKit.getSkDataBytes(skimg);
71 return 'data:' + codec + ';base64,' + toBase64String(imgBytes);
72 }
73
74 this.dispose = function() {
75 this._context._dispose();
Kevin Lubick8e4a3312018-12-14 15:03:41 -050076 this._toCleanup.forEach(function(i) {
Kevin Lubick53eabf62018-12-10 12:41:26 -050077 i.delete();
78 });
79 this._surface.dispose();
80 }
81}