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