• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  this._fontmgr = CanvasKit.SkFontMgr.RefDefault();
14
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    }
21    this._toCleanup.push(img);
22    return img;
23  }
24
25  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
35  this.makePath2D = function(path) {
36    var p2d = new Path2D(path);
37    this._toCleanup.push(p2d._getPath());
38    return p2d;
39  }
40
41  // 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();
76    this._toCleanup.forEach(function(i) {
77      i.delete();
78    });
79    this._surface.dispose();
80  }
81}