1CanvasKit.MakeCanvas = function(width, height) { 2 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._toCleanup = []; 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._toCleanup.push(img); 21 return img; 22 }; 23 24 this.loadFont = function(buffer, descriptors) { 25 var newFont = CanvasKit.Typeface.MakeFreeTypeFaceFromData(buffer); 26 if (!newFont) { 27 Debug('font could not be processed', descriptors); 28 return null; 29 } 30 this._toCleanup.push(newFont); 31 addToFontCache(newFont, descriptors); 32 }; 33 34 this.makePath2D = function(path) { 35 var p2d = new Path2D(path); 36 this._toCleanup.push(p2d._getPath()); 37 return p2d; 38 }; 39 40 // A normal <canvas> requires that clients call getContext 41 this.getContext = function(type) { 42 if (type === '2d') { 43 return this._context; 44 } 45 return null; 46 }; 47 48 this.toDataURL = function(codec, quality) { 49 // TODO(kjlubick): maybe support other codecs (webp?) 50 // For now, just to png and jpeg 51 this._surface.flush(); 52 53 var img = this._surface.makeImageSnapshot(); 54 if (!img) { 55 Debug('no snapshot'); 56 return; 57 } 58 codec = codec || 'image/png'; 59 var format = CanvasKit.ImageFormat.PNG; 60 if (codec === 'image/jpeg') { 61 format = CanvasKit.ImageFormat.JPEG; 62 } 63 quality = quality || 0.92; 64 var imgBytes = img.encodeToBytes(format, quality); 65 if (!imgBytes) { 66 Debug('encoding failure'); 67 return 68 } 69 img.delete(); 70 return 'data:' + codec + ';base64,' + toBase64String(imgBytes); 71 }; 72 73 this.dispose = function() { 74 this._context._dispose(); 75 this._toCleanup.forEach(function(i) { 76 i.delete(); 77 }); 78 this._surface.dispose(); 79 } 80} 81