blob: 1c2ec5f7652828277ebd4a39b7acc56e2405a89c [file] [log] [blame]
Kevin Lubick217056c2018-09-20 17:39:31 -04001// Adds JS functions to augment the CanvasKit interface.
2// For example, if there is a wrapper around the C++ call or logic to allow
3// chaining, it should go here.
Kevin Lubick1a05fce2018-11-20 12:51:16 -05004
Kevin Lubickf5ea37f2019-02-28 10:06:18 -05005// CanvasKit.onRuntimeInitialized is called after the WASM library has loaded.
6// Anything that modifies an exposed class (e.g. SkPath) should be set
7// after onRuntimeInitialized, otherwise, it can happen outside of that scope.
8CanvasKit.onRuntimeInitialized = function() {
9 // All calls to 'this' need to go in externs.js so closure doesn't minify them away.
Kevin Lubick1a05fce2018-11-20 12:51:16 -050010
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050011 // Add some helpers for matrices. This is ported from SkMatrix.cpp
12 // to save complexity and overhead of going back and forth between
13 // C++ and JS layers.
14 // I would have liked to use something like DOMMatrix, except it
15 // isn't widely supported (would need polyfills) and it doesn't
16 // have a mapPoints() function (which could maybe be tacked on here).
17 // If DOMMatrix catches on, it would be worth re-considering this usage.
18 CanvasKit.SkMatrix = {};
19 function sdot(a, b, c, d, e, f) {
20 e = e || 0;
21 f = f || 0;
22 return a * b + c * d + e * f;
23 }
24
25 CanvasKit.SkMatrix.identity = function() {
26 return [
27 1, 0, 0,
28 0, 1, 0,
29 0, 0, 1,
30 ];
31 };
32
33 // Return the inverse (if it exists) of this matrix.
34 // Otherwise, return the identity.
35 CanvasKit.SkMatrix.invert = function(m) {
36 var det = m[0]*m[4]*m[8] + m[1]*m[5]*m[6] + m[2]*m[3]*m[7]
37 - m[2]*m[4]*m[6] - m[1]*m[3]*m[8] - m[0]*m[5]*m[7];
38 if (!det) {
39 SkDebug('Warning, uninvertible matrix');
40 return CanvasKit.SkMatrix.identity();
Kevin Lubick1a05fce2018-11-20 12:51:16 -050041 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050042 return [
43 (m[4]*m[8] - m[5]*m[7])/det, (m[2]*m[7] - m[1]*m[8])/det, (m[1]*m[5] - m[2]*m[4])/det,
44 (m[5]*m[6] - m[3]*m[8])/det, (m[0]*m[8] - m[2]*m[6])/det, (m[2]*m[3] - m[0]*m[5])/det,
45 (m[3]*m[7] - m[4]*m[6])/det, (m[1]*m[6] - m[0]*m[7])/det, (m[0]*m[4] - m[1]*m[3])/det,
46 ];
47 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -050048
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050049 // Maps the given points according to the passed in matrix.
50 // Results are done in place.
51 // See SkMatrix.h::mapPoints for the docs on the math.
52 CanvasKit.SkMatrix.mapPoints = function(matrix, ptArr) {
53 if (ptArr.length % 2) {
54 throw 'mapPoints requires an even length arr';
Kevin Lubickb9db3902018-11-26 11:47:54 -050055 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050056 for (var i = 0; i < ptArr.length; i+=2) {
57 var x = ptArr[i], y = ptArr[i+1];
58 // Gx+Hy+I
59 var denom = matrix[6]*x + matrix[7]*y + matrix[8];
60 // Ax+By+C
61 var xTrans = matrix[0]*x + matrix[1]*y + matrix[2];
62 // Dx+Ey+F
63 var yTrans = matrix[3]*x + matrix[4]*y + matrix[5];
64 ptArr[i] = xTrans/denom;
65 ptArr[i+1] = yTrans/denom;
66 }
67 return ptArr;
68 };
Kevin Lubickb9db3902018-11-26 11:47:54 -050069
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050070 CanvasKit.SkMatrix.multiply = function(m1, m2) {
71 var result = [0,0,0, 0,0,0, 0,0,0];
72 for (var r = 0; r < 3; r++) {
73 for (var c = 0; c < 3; c++) {
74 // m1 and m2 are 1D arrays pretending to be 2D arrays
75 result[3*r + c] = sdot(m1[3*r + 0], m2[3*0 + c],
76 m1[3*r + 1], m2[3*1 + c],
77 m1[3*r + 2], m2[3*2 + c]);
Kevin Lubick1a05fce2018-11-20 12:51:16 -050078 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050079 }
80 return result;
81 }
Kevin Lubick1a05fce2018-11-20 12:51:16 -050082
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050083 // Return a matrix representing a rotation by n radians.
84 // px, py optionally say which point the rotation should be around
85 // with the default being (0, 0);
86 CanvasKit.SkMatrix.rotated = function(radians, px, py) {
87 px = px || 0;
88 py = py || 0;
89 var sinV = Math.sin(radians);
90 var cosV = Math.cos(radians);
91 return [
92 cosV, -sinV, sdot( sinV, py, 1 - cosV, px),
93 sinV, cosV, sdot(-sinV, px, 1 - cosV, py),
94 0, 0, 1,
95 ];
96 };
Kevin Lubick217056c2018-09-20 17:39:31 -040097
Kevin Lubickf5ea37f2019-02-28 10:06:18 -050098 CanvasKit.SkMatrix.scaled = function(sx, sy, px, py) {
99 px = px || 0;
100 py = py || 0;
101 return [
102 sx, 0, px - sx * px,
103 0, sy, py - sy * py,
104 0, 0, 1,
105 ];
106 };
Kevin Lubickda3d8ac2019-01-07 11:08:55 -0500107
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500108 CanvasKit.SkMatrix.skewed = function(kx, ky, px, py) {
109 px = px || 0;
110 py = py || 0;
111 return [
112 1, kx, -kx * px,
113 ky, 1, -ky * py,
114 0, 0, 1,
115 ];
116 };
Alexander Khovansky3e119332018-11-15 02:01:19 +0300117
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500118 CanvasKit.SkMatrix.translated = function(dx, dy) {
119 return [
120 1, 0, dx,
121 0, 1, dy,
122 0, 0, 1,
123 ];
124 };
Kevin Lubick1646e7d2018-12-07 13:03:08 -0500125
Kevin Lubickd3729342019-09-12 11:11:25 -0400126 // An SkColorMatrix is a 4x4 color matrix that transforms the 4 color channels
127 // with a 1x4 matrix that post-translates those 4 channels.
128 // For example, the following is the layout with the scale (S) and post-transform
129 // (PT) items indicated.
130 // RS, 0, 0, 0 | RPT
131 // 0, GS, 0, 0 | GPT
132 // 0, 0, BS, 0 | BPT
133 // 0, 0, 0, AS | APT
134 //
135 // Much of this was hand-transcribed from SkColorMatrix.cpp, because it's easier to
136 // deal with a Float32Array of length 20 than to try to expose the SkColorMatrix object.
137
138 var rScale = 0;
139 var gScale = 6;
140 var bScale = 12;
141 var aScale = 18;
142
143 var rPostTrans = 4;
144 var gPostTrans = 9;
145 var bPostTrans = 14;
146 var aPostTrans = 19;
147
148 CanvasKit.SkColorMatrix = {};
149 CanvasKit.SkColorMatrix.identity = function() {
150 var m = new Float32Array(20);
151 m[rScale] = 1;
152 m[gScale] = 1;
153 m[bScale] = 1;
154 m[aScale] = 1;
155 return m;
156 }
157
158 CanvasKit.SkColorMatrix.scaled = function(rs, gs, bs, as) {
159 var m = new Float32Array(20);
160 m[rScale] = rs;
161 m[gScale] = gs;
162 m[bScale] = bs;
163 m[aScale] = as;
164 return m;
165 }
166
167 var rotateIndices = [
168 [6, 7, 11, 12],
169 [0, 10, 2, 12],
170 [0, 1, 5, 6],
171 ];
172 // axis should be 0, 1, 2 for r, g, b
173 CanvasKit.SkColorMatrix.rotated = function(axis, sine, cosine) {
174 var m = CanvasKit.SkColorMatrix.identity();
175 var indices = rotateIndices[axis];
176 m[indices[0]] = cosine;
177 m[indices[1]] = sine;
178 m[indices[2]] = -sine;
179 m[indices[3]] = cosine;
180 return m;
181 }
182
183 // m is a SkColorMatrix (i.e. a Float32Array), and this sets the 4 "special"
184 // params that will translate the colors after they are multiplied by the 4x4 matrix.
185 CanvasKit.SkColorMatrix.postTranslate = function(m, dr, dg, db, da) {
186 m[rPostTrans] += dr;
187 m[gPostTrans] += dg;
188 m[bPostTrans] += db;
189 m[aPostTrans] += da;
190 return m;
191 }
192
193 // concat returns a new SkColorMatrix that is the result of multiplying outer*inner;
194 CanvasKit.SkColorMatrix.concat = function(outer, inner) {
195 var m = new Float32Array(20);
196 var index = 0;
197 for (var j = 0; j < 20; j += 5) {
198 for (var i = 0; i < 4; i++) {
199 m[index++] = outer[j + 0] * inner[i + 0] +
200 outer[j + 1] * inner[i + 5] +
201 outer[j + 2] * inner[i + 10] +
202 outer[j + 3] * inner[i + 15];
203 }
204 m[index++] = outer[j + 0] * inner[4] +
205 outer[j + 1] * inner[9] +
206 outer[j + 2] * inner[14] +
207 outer[j + 3] * inner[19] +
208 outer[j + 4];
209 }
210
211 return m;
212 }
213
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500214 CanvasKit.SkPath.prototype.addArc = function(oval, startAngle, sweepAngle) {
215 // see arc() for the HTMLCanvas version
216 // note input angles are degrees.
217 this._addArc(oval, startAngle, sweepAngle);
218 return this;
219 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400220
Kevin Lubicke384df42019-08-26 15:48:09 -0400221 CanvasKit.SkPath.prototype.addOval = function(oval, isCCW, startIndex) {
222 if (startIndex === undefined) {
223 startIndex = 1;
224 }
225 this._addOval(oval, !!isCCW, startIndex);
226 return this;
227 };
228
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500229 CanvasKit.SkPath.prototype.addPath = function() {
230 // Takes 1, 2, 7, or 10 required args, where the first arg is always the path.
231 // The last arg is optional and chooses between add or extend mode.
232 // The options for the remaining args are:
233 // - an array of 6 or 9 parameters (perspective is optional)
234 // - the 9 parameters of a full matrix or
235 // the 6 non-perspective params of a matrix.
236 var args = Array.prototype.slice.call(arguments);
237 var path = args[0];
238 var extend = false;
239 if (typeof args[args.length-1] === "boolean") {
240 extend = args.pop();
241 }
242 if (args.length === 1) {
243 // Add path, unchanged. Use identity matrix
244 this._addPath(path, 1, 0, 0,
245 0, 1, 0,
246 0, 0, 1,
247 extend);
248 } else if (args.length === 2) {
249 // User provided the 9 params of a full matrix as an array.
250 var a = args[1];
251 this._addPath(path, a[0], a[1], a[2],
252 a[3], a[4], a[5],
253 a[6] || 0, a[7] || 0, a[8] || 1,
254 extend);
255 } else if (args.length === 7 || args.length === 10) {
256 // User provided the 9 params of a (full) matrix directly.
257 // (or just the 6 non perspective ones)
258 // These are in the same order as what Skia expects.
259 var a = args;
260 this._addPath(path, a[1], a[2], a[3],
261 a[4], a[5], a[6],
262 a[7] || 0, a[8] || 0, a[9] || 1,
263 extend);
264 } else {
265 SkDebug('addPath expected to take 1, 2, 7, or 10 required args. Got ' + args.length);
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400266 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500267 }
268 return this;
269 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400270
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500271 // points is either an array of [x, y] where x and y are numbers or
272 // a typed array from Malloc where the even indices will be treated
273 // as x coordinates and the odd indices will be treated as y coordinates.
274 CanvasKit.SkPath.prototype.addPoly = function(points, close) {
275 var ptr;
276 var n;
277 // This was created with CanvasKit.Malloc, so assume the user has
278 // already been filled with data.
279 if (points['_ck']) {
280 ptr = points.byteOffset;
281 n = points.length/2;
282 } else {
283 ptr = copy2dArray(points, CanvasKit.HEAPF32);
284 n = points.length;
285 }
286 this._addPoly(ptr, n, close);
287 CanvasKit._free(ptr);
288 return this;
289 };
290
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500291 CanvasKit.SkPath.prototype.addRect = function() {
292 // Takes 1, 2, 4 or 5 args
293 // - SkRect
294 // - SkRect, isCCW
295 // - left, top, right, bottom
296 // - left, top, right, bottom, isCCW
297 if (arguments.length === 1 || arguments.length === 2) {
298 var r = arguments[0];
299 var ccw = arguments[1] || false;
300 this._addRect(r.fLeft, r.fTop, r.fRight, r.fBottom, ccw);
301 } else if (arguments.length === 4 || arguments.length === 5) {
302 var a = arguments;
303 this._addRect(a[0], a[1], a[2], a[3], a[4] || false);
304 } else {
305 SkDebug('addRect expected to take 1, 2, 4, or 5 args. Got ' + arguments.length);
Kevin Lubick217056c2018-09-20 17:39:31 -0400306 return null;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500307 }
308 return this;
309 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400310
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500311 CanvasKit.SkPath.prototype.addRoundRect = function() {
312 // Takes 3, 4, 6 or 7 args
313 // - SkRect, radii, ccw
314 // - SkRect, rx, ry, ccw
315 // - left, top, right, bottom, radii, ccw
316 // - left, top, right, bottom, rx, ry, ccw
317 var args = arguments;
318 if (args.length === 3 || args.length === 6) {
319 var radii = args[args.length-2];
320 } else if (args.length === 6 || args.length === 7){
321 // duplicate the given (rx, ry) pairs for each corner.
322 var rx = args[args.length-3];
323 var ry = args[args.length-2];
324 var radii = [rx, ry, rx, ry, rx, ry, rx, ry];
325 } else {
326 SkDebug('addRoundRect expected to take 3, 4, 6, or 7 args. Got ' + args.length);
327 return null;
328 }
329 if (radii.length !== 8) {
330 SkDebug('addRoundRect needs 8 radii provided. Got ' + radii.length);
331 return null;
332 }
333 var rptr = copy1dArray(radii, CanvasKit.HEAPF32);
334 if (args.length === 3 || args.length === 4) {
335 var r = args[0];
336 var ccw = args[args.length - 1];
337 this._addRoundRect(r.fLeft, r.fTop, r.fRight, r.fBottom, rptr, ccw);
338 } else if (args.length === 6 || args.length === 7) {
339 var a = args;
340 this._addRoundRect(a[0], a[1], a[2], a[3], rptr, ccw);
341 }
342 CanvasKit._free(rptr);
343 return this;
344 };
345
346 CanvasKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) {
347 // emulates the HTMLCanvas behavior. See addArc() for the SkPath version.
348 // Note input angles are radians.
349 var bounds = CanvasKit.LTRBRect(x-radius, y-radius, x+radius, y+radius);
350 var sweep = radiansToDegrees(endAngle - startAngle) - (360 * !!ccw);
351 var temp = new CanvasKit.SkPath();
352 temp.addArc(bounds, radiansToDegrees(startAngle), sweep);
353 this.addPath(temp, true);
354 temp.delete();
355 return this;
356 };
357
358 CanvasKit.SkPath.prototype.arcTo = function() {
359 // takes 4, 5 or 7 args
360 // - 5 x1, y1, x2, y2, radius
361 // - 4 oval (as Rect), startAngle, sweepAngle, forceMoveTo
Kevin Lubicke384df42019-08-26 15:48:09 -0400362 // - 7 rx, ry, xAxisRotate, useSmallArc, isCCW, x, y
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500363 var args = arguments;
364 if (args.length === 5) {
365 this._arcTo(args[0], args[1], args[2], args[3], args[4]);
366 } else if (args.length === 4) {
367 this._arcTo(args[0], args[1], args[2], args[3]);
368 } else if (args.length === 7) {
Kevin Lubicke384df42019-08-26 15:48:09 -0400369 this._arcTo(args[0], args[1], args[2], !!args[3], !!args[4], args[5], args[6]);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500370 } else {
371 throw 'Invalid args for arcTo. Expected 4, 5, or 7, got '+ args.length;
372 }
373
374 return this;
375 };
376
377 CanvasKit.SkPath.prototype.close = function() {
378 this._close();
379 return this;
380 };
381
382 CanvasKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) {
383 this._conicTo(x1, y1, x2, y2, w);
384 return this;
385 };
386
387 CanvasKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
388 this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
389 return this;
390 };
391
392 CanvasKit.SkPath.prototype.dash = function(on, off, phase) {
393 if (this._dash(on, off, phase)) {
Kevin Lubick217056c2018-09-20 17:39:31 -0400394 return this;
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500395 }
396 return null;
397 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400398
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500399 CanvasKit.SkPath.prototype.lineTo = function(x, y) {
400 this._lineTo(x, y);
401 return this;
402 };
Kevin Lubick217056c2018-09-20 17:39:31 -0400403
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500404 CanvasKit.SkPath.prototype.moveTo = function(x, y) {
405 this._moveTo(x, y);
406 return this;
407 };
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400408
Kevin Lubicke384df42019-08-26 15:48:09 -0400409 CanvasKit.SkPath.prototype.offset = function(dx, dy) {
410 this._transform(1, 0, dx,
411 0, 1, dy,
412 0, 0, 1);
413 return this;
414 };
415
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500416 CanvasKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) {
417 this._quadTo(cpx, cpy, x, y);
418 return this;
419 };
420
Kevin Lubick79b71342019-11-01 14:36:52 -0400421 CanvasKit.SkPath.prototype.rArcTo = function(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy) {
422 this._rArcTo(rx, ry, xAxisRotate, useSmallArc, isCCW, dx, dy);
423 return this;
424 };
425
426 CanvasKit.SkPath.prototype.rConicTo = function(dx1, dy1, dx2, dy2, w) {
427 this._rConicTo(dx1, dy1, dx2, dy2, w);
428 return this;
429 };
430
431 // These params are all relative
432 CanvasKit.SkPath.prototype.rCubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
433 this._rCubicTo(cp1x, cp1y, cp2x, cp2y, x, y);
434 return this;
435 };
436
437 CanvasKit.SkPath.prototype.rLineTo = function(dx, dy) {
438 this._rLineTo(dx, dy);
439 return this;
440 };
441
442 CanvasKit.SkPath.prototype.rMoveTo = function(dx, dy) {
443 this._rMoveTo(dx, dy);
444 return this;
445 };
446
447 // These params are all relative
448 CanvasKit.SkPath.prototype.rQuadTo = function(cpx, cpy, x, y) {
449 this._rQuadTo(cpx, cpy, x, y);
450 return this;
451 };
452
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500453 CanvasKit.SkPath.prototype.stroke = function(opts) {
454 // Fill out any missing values with the default values.
455 /**
456 * See externs.js for this definition
457 * @type {StrokeOpts}
458 */
459 opts = opts || {};
460 opts.width = opts.width || 1;
461 opts.miter_limit = opts.miter_limit || 4;
462 opts.cap = opts.cap || CanvasKit.StrokeCap.Butt;
463 opts.join = opts.join || CanvasKit.StrokeJoin.Miter;
464 opts.precision = opts.precision || 1;
465 if (this._stroke(opts)) {
466 return this;
467 }
468 return null;
469 };
470
471 CanvasKit.SkPath.prototype.transform = function() {
472 // Takes 1 or 9 args
473 if (arguments.length === 1) {
474 // argument 1 should be a 6 or 9 element array.
475 var a = arguments[0];
476 this._transform(a[0], a[1], a[2],
477 a[3], a[4], a[5],
478 a[6] || 0, a[7] || 0, a[8] || 1);
479 } else if (arguments.length === 6 || arguments.length === 9) {
480 // these arguments are the 6 or 9 members of the matrix
481 var a = arguments;
482 this._transform(a[0], a[1], a[2],
483 a[3], a[4], a[5],
484 a[6] || 0, a[7] || 0, a[8] || 1);
485 } else {
486 throw 'transform expected to take 1 or 9 arguments. Got ' + arguments.length;
487 }
488 return this;
489 };
490 // isComplement is optional, defaults to false
491 CanvasKit.SkPath.prototype.trim = function(startT, stopT, isComplement) {
492 if (this._trim(startT, stopT, !!isComplement)) {
493 return this;
494 }
495 return null;
496 };
497
498 // bones should be a 3d array.
499 // Each bone is a 3x2 transformation matrix in column major order:
500 // | scaleX skewX transX |
501 // | skewY scaleY transY |
502 // and bones is an array of those matrices.
503 // Returns a copy of this (SkVertices) with the bones applied.
504 CanvasKit.SkVertices.prototype.applyBones = function(bones) {
505 var bPtr = copy3dArray(bones, CanvasKit.HEAPF32);
506 var vert = this._applyBones(bPtr, bones.length);
507 CanvasKit._free(bPtr);
508 return vert;
509 }
510
511 CanvasKit.SkImage.prototype.encodeToData = function() {
512 if (!arguments.length) {
513 return this._encodeToData();
Kevin Lubickb5ae3b52018-11-03 07:51:19 -0400514 }
Kevin Lubick53965c92018-10-11 08:51:55 -0400515
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500516 if (arguments.length === 2) {
517 var a = arguments;
518 return this._encodeToDataWithFormat(a[0], a[1]);
Alexander Khovansky3e119332018-11-15 02:01:19 +0300519 }
520
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500521 throw 'encodeToData expected to take 0 or 2 arguments. Got ' + arguments.length;
522 }
Kevin Lubick1ba9c4d2019-02-22 10:04:06 -0500523
Kevin Lubicka064c282019-04-04 09:28:53 -0400524 CanvasKit.SkImage.prototype.makeShader = function(xTileMode, yTileMode, localMatrix) {
525 if (localMatrix) {
526 // Add perspective args if not provided.
527 if (localMatrix.length === 6) {
528 localMatrix.push(0, 0, 1);
529 }
530 return this._makeShader(xTileMode, yTileMode, localMatrix);
531 } else {
532 return this._makeShader(xTileMode, yTileMode);
533 }
534 }
535
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400536 CanvasKit.SkImage.prototype.readPixels = function(imageInfo, srcX, srcY) {
537 var rowBytes;
Kevin Lubick319524b2020-01-22 15:29:14 -0500538 // Important to use ["string"] notation here, otherwise the closure compiler will
539 // minify away the colorType.
540 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400541 case CanvasKit.ColorType.RGBA_8888:
542 rowBytes = imageInfo.width * 4; // 1 byte per channel == 4 bytes per pixel in 8888
543 break;
544 case CanvasKit.ColorType.RGBA_F32:
545 rowBytes = imageInfo.width * 16; // 4 bytes per channel == 16 bytes per pixel in F32
546 break;
547 default:
548 SkDebug("Colortype not yet supported");
549 return;
550 }
551 var pBytes = rowBytes * imageInfo.height;
552 var pPtr = CanvasKit._malloc(pBytes);
553
554 if (!this._readPixels(imageInfo, pPtr, rowBytes, srcX, srcY)) {
555 SkDebug("Could not read pixels with the given inputs");
556 return null;
557 }
558
559 // Put those pixels into a typed array of the right format and then
560 // make a copy with slice() that we can return.
561 var retVal = null;
Kevin Lubick319524b2020-01-22 15:29:14 -0500562 switch (imageInfo["colorType"]) {
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400563 case CanvasKit.ColorType.RGBA_8888:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800564 retVal = new Uint8Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400565 break;
566 case CanvasKit.ColorType.RGBA_F32:
Bryce Thomas1fa54042020-01-14 13:46:30 -0800567 retVal = new Float32Array(CanvasKit.HEAPU8.buffer, pPtr, pBytes).slice();
Kevin Lubickd6b32ed2019-05-06 13:04:03 -0400568 break;
569 }
570
571 // Free the allocated pixels in the WASM memory
572 CanvasKit._free(pPtr);
573 return retVal;
574
575 }
576
Kevin Lubickee91c072019-03-29 10:39:52 -0400577 // atlas is an SkImage, e.g. from CanvasKit.MakeImageFromEncoded
578 // srcRects and dstXforms should be CanvasKit.SkRectBuilder and CanvasKit.RSXFormBuilder
579 // or just arrays of floats in groups of 4.
580 // colors, if provided, should be a CanvasKit.SkColorBuilder or array of SkColor
581 // (from CanvasKit.Color)
582 CanvasKit.SkCanvas.prototype.drawAtlas = function(atlas, srcRects, dstXforms, paint,
583 /*optional*/ blendMode, colors) {
584 if (!atlas || !paint || !srcRects || !dstXforms) {
585 SkDebug('Doing nothing since missing a required input');
586 return;
587 }
588 if (srcRects.length !== dstXforms.length || (colors && colors.length !== dstXforms.length)) {
589 SkDebug('Doing nothing since input arrays length mismatches');
590 }
591 if (!blendMode) {
592 blendMode = CanvasKit.BlendMode.SrcOver;
593 }
594
595 var srcRectPtr;
596 if (srcRects.build) {
597 srcRectPtr = srcRects.build();
598 } else {
599 srcRectPtr = copy1dArray(srcRects, CanvasKit.HEAPF32);
600 }
601
602 var dstXformPtr;
603 if (dstXforms.build) {
604 dstXformPtr = dstXforms.build();
605 } else {
606 dstXformPtr = copy1dArray(dstXforms, CanvasKit.HEAPF32);
607 }
608
609 var colorPtr = 0; // enscriptem doesn't like undefined for nullptr
610 if (colors) {
611 if (colors.build) {
612 colorPtr = colors.build();
613 } else {
614 colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
615 }
616 }
617
618 this._drawAtlas(atlas, dstXformPtr, srcRectPtr, colorPtr, dstXforms.length,
619 blendMode, paint);
620
621 if (srcRectPtr && !srcRects.build) {
622 CanvasKit._free(srcRectPtr);
623 }
624 if (dstXformPtr && !dstXforms.build) {
625 CanvasKit._free(dstXformPtr);
626 }
627 if (colorPtr && !colors.build) {
628 CanvasKit._free(colorPtr);
629 }
630
631 }
632
Kevin Lubick37ab53e2019-11-11 10:06:08 -0500633 // points is either an array of [x, y] where x and y are numbers or
634 // a typed array from Malloc where the even indices will be treated
635 // as x coordinates and the odd indices will be treated as y coordinates.
636 CanvasKit.SkCanvas.prototype.drawPoints = function(mode, points, paint) {
637 var ptr;
638 var n;
639 // This was created with CanvasKit.Malloc, so assume the user has
640 // already been filled with data.
641 if (points['_ck']) {
642 ptr = points.byteOffset;
643 n = points.length/2;
644 } else {
645 ptr = copy2dArray(points, CanvasKit.HEAPF32);
646 n = points.length;
647 }
648 this._drawPoints(mode, ptr, n, paint);
649 CanvasKit._free(ptr);
650 }
651
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500652 // returns Uint8Array
653 CanvasKit.SkCanvas.prototype.readPixels = function(x, y, w, h, alphaType,
654 colorType, dstRowBytes) {
655 // supply defaults (which are compatible with HTMLCanvas's getImageData)
656 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
657 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
658 dstRowBytes = dstRowBytes || (4 * w);
659
660 var len = h * dstRowBytes
661 var pptr = CanvasKit._malloc(len);
662 var ok = this._readPixels({
663 'width': w,
664 'height': h,
Kevin Lubick52b9f372018-12-04 13:57:36 -0500665 'colorType': colorType,
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500666 'alphaType': alphaType,
667 }, pptr, dstRowBytes, x, y);
668 if (!ok) {
669 CanvasKit._free(pptr);
670 return null;
671 }
672
673 // The first typed array is just a view into memory. Because we will
674 // be free-ing that, we call slice to make a persistent copy.
Bryce Thomas1fa54042020-01-14 13:46:30 -0800675 var pixels = new Uint8Array(CanvasKit.HEAPU8.buffer, pptr, len).slice();
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500676 CanvasKit._free(pptr);
677 return pixels;
678 }
679
680 // pixels is a TypedArray. No matter the input size, it will be treated as
681 // a Uint8Array (essentially, a byte array).
682 CanvasKit.SkCanvas.prototype.writePixels = function(pixels, srcWidth, srcHeight,
683 destX, destY, alphaType, colorType) {
684 if (pixels.byteLength % (srcWidth * srcHeight)) {
685 throw 'pixels length must be a multiple of the srcWidth * srcHeight';
686 }
687 var bytesPerPixel = pixels.byteLength / (srcWidth * srcHeight);
688 // supply defaults (which are compatible with HTMLCanvas's putImageData)
689 alphaType = alphaType || CanvasKit.AlphaType.Unpremul;
690 colorType = colorType || CanvasKit.ColorType.RGBA_8888;
691 var srcRowBytes = bytesPerPixel * srcWidth;
692
Kevin Lubick52b9f372018-12-04 13:57:36 -0500693 var pptr = CanvasKit._malloc(pixels.byteLength);
694 CanvasKit.HEAPU8.set(pixels, pptr);
Kevin Lubick52b9f372018-12-04 13:57:36 -0500695
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500696 var ok = this._writePixels({
697 'width': srcWidth,
698 'height': srcHeight,
699 'colorType': colorType,
700 'alphaType': alphaType,
701 }, pptr, srcRowBytes, destX, destY);
702
703 CanvasKit._free(pptr);
704 return ok;
Kevin Lubick52b9f372018-12-04 13:57:36 -0500705 }
706
Kevin Lubickd3729342019-09-12 11:11:25 -0400707 // colorMatrix is an SkColorMatrix (e.g. Float32Array of length 20)
708 CanvasKit.SkColorFilter.MakeMatrix = function(colorMatrix) {
709 if (!colorMatrix || colorMatrix.length !== 20) {
710 SkDebug('ignoring invalid color matrix');
711 return;
712 }
713 var fptr = copy1dArray(colorMatrix, CanvasKit.HEAPF32);
714 // We know skia memcopies the floats, so we can free our memory after the call returns.
715 var m = CanvasKit.SkColorFilter._makeMatrix(fptr);
716 CanvasKit._free(fptr);
717 return m;
718 }
719
Kevin Lubick62836902019-12-09 09:04:26 -0500720 CanvasKit.SkShader.Blend = function(mode, dst, src, localMatrix) {
721 if (!localMatrix) {
722 return this._Blend(mode, dst, src);
723 }
724 return this._Blend(mode, dst, src, localMatrix);
725 }
726
727 CanvasKit.SkShader.Lerp = function(t, dst, src, localMatrix) {
728 if (!localMatrix) {
729 return this._Lerp(t, dst, src);
730 }
731 return this._Lerp(t, dst, src, localMatrix);
732 }
733
Kevin Lubickcc13fd32019-04-05 13:00:01 -0400734 CanvasKit.SkSurface.prototype.captureFrameAsSkPicture = function(drawFrame) {
735 // Set up SkPictureRecorder
736 var spr = new CanvasKit.SkPictureRecorder();
737 var canvas = spr.beginRecording(
738 CanvasKit.LTRBRect(0, 0, this.width(), this.height()));
739 drawFrame(canvas);
740 var pic = spr.finishRecordingAsPicture();
741 spr.delete();
742 // TODO: do we need to clean up the memory for canvas?
743 // If we delete it here, saveAsFile doesn't work correctly.
744 return pic;
745 }
746
Kevin Lubick359a7e32019-03-19 09:34:37 -0400747 CanvasKit.SkSurface.prototype.requestAnimationFrame = function(callback, dirtyRect) {
748 if (!this._cached_canvas) {
749 this._cached_canvas = this.getCanvas();
750 }
751 window.requestAnimationFrame(function() {
Kevin Lubick39026282019-03-28 12:46:40 -0400752 if (this._context !== undefined) {
753 CanvasKit.setCurrentContext(this._context);
754 }
Kevin Lubick359a7e32019-03-19 09:34:37 -0400755
756 callback(this._cached_canvas);
757
Bryce Thomas2c5b8562020-01-22 13:49:41 -0800758 // We do not dispose() of the SkSurface here, as the client will typically
759 // call requestAnimationFrame again from within the supplied callback.
760 // For drawing a single frame, prefer drawOnce().
Kevin Lubick359a7e32019-03-19 09:34:37 -0400761 this.flush();
762 }.bind(this));
763 }
764
Bryce Thomas2c5b8562020-01-22 13:49:41 -0800765 CanvasKit.SkSurface.prototype.drawOnce = function(callback, dirtyRect) {
766 if (!this._cached_canvas) {
767 this._cached_canvas = this.getCanvas();
768 }
769 window.requestAnimationFrame(function() {
770 if (this._context !== undefined) {
771 CanvasKit.setCurrentContext(this._context);
772 }
773 callback(this._cached_canvas);
774
775 this.flush();
776 this.dispose();
777 }.bind(this));
778 }
779
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500780 // Run through the JS files that are added at compile time.
781 if (CanvasKit._extraInitializations) {
782 CanvasKit._extraInitializations.forEach(function(init) {
783 init();
784 });
Kevin Lubickeb2f6b02018-11-29 15:07:02 -0500785 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500786}; // end CanvasKit.onRuntimeInitialized, that is, anything changing prototypes or dynamic.
Kevin Lubickeb2f6b02018-11-29 15:07:02 -0500787
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500788CanvasKit.LTRBRect = function(l, t, r, b) {
789 return {
790 fLeft: l,
791 fTop: t,
792 fRight: r,
793 fBottom: b,
794 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500795}
796
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500797CanvasKit.XYWHRect = function(x, y, w, h) {
798 return {
799 fLeft: x,
800 fTop: y,
801 fRight: x+w,
802 fBottom: y+h,
803 };
Kevin Lubick1a05fce2018-11-20 12:51:16 -0500804}
805
Kevin Lubick7d644e12019-09-11 14:22:22 -0400806// RRectXY returns an RRect with the given rect and a radiusX and radiusY for
807// all 4 corners.
808CanvasKit.RRectXY = function(rect, rx, ry) {
809 return {
810 rect: rect,
811 rx1: rx,
812 ry1: ry,
813 rx2: rx,
814 ry2: ry,
815 rx3: rx,
816 ry3: ry,
817 rx4: rx,
818 ry4: ry,
819 };
820}
821
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500822CanvasKit.MakePathFromCmds = function(cmds) {
823 var ptrLen = loadCmdsTypedArray(cmds);
824 var path = CanvasKit._MakePathFromCmds(ptrLen[0], ptrLen[1]);
825 CanvasKit._free(ptrLen[0]);
826 return path;
827}
828
829CanvasKit.MakeSkDashPathEffect = function(intervals, phase) {
830 if (!phase) {
831 phase = 0;
832 }
833 if (!intervals.length || intervals.length % 2 === 1) {
834 throw 'Intervals array must have even length';
835 }
836 var ptr = copy1dArray(intervals, CanvasKit.HEAPF32);
837 var dpe = CanvasKit._MakeSkDashPathEffect(ptr, intervals.length, phase);
838 CanvasKit._free(ptr);
839 return dpe;
840}
841
842// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubick6b921b72019-09-18 16:18:17 -0400843CanvasKit.MakeAnimatedImageFromEncoded = function(data) {
844 data = new Uint8Array(data);
845
846 var iptr = CanvasKit._malloc(data.byteLength);
847 CanvasKit.HEAPU8.set(data, iptr);
848 var img = CanvasKit._decodeAnimatedImage(iptr, data.byteLength);
849 if (!img) {
850 SkDebug('Could not decode animated image');
851 return null;
852 }
853 return img;
854}
855
856// data is a TypedArray or ArrayBuffer e.g. from fetch().then(resp.arrayBuffer())
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500857CanvasKit.MakeImageFromEncoded = function(data) {
858 data = new Uint8Array(data);
859
860 var iptr = CanvasKit._malloc(data.byteLength);
861 CanvasKit.HEAPU8.set(data, iptr);
862 var img = CanvasKit._decodeImage(iptr, data.byteLength);
863 if (!img) {
864 SkDebug('Could not decode image');
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500865 return null;
866 }
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500867 return img;
868}
869
Kevin Lubickeda0b432019-12-02 08:26:48 -0500870// pixels must be a Uint8Array with bytes representing the pixel values
871// (e.g. each set of 4 bytes could represent RGBA values for a single pixel).
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500872CanvasKit.MakeImage = function(pixels, width, height, alphaType, colorType) {
Kevin Lubickeda0b432019-12-02 08:26:48 -0500873 var bytesPerPixel = pixels.length / (width * height);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500874 var info = {
875 'width': width,
876 'height': height,
877 'alphaType': alphaType,
878 'colorType': colorType,
879 };
Kevin Lubickeda0b432019-12-02 08:26:48 -0500880 var pptr = copy1dArray(pixels, CanvasKit.HEAPU8);
881 // No need to _free pptr, Image takes it with SkData::MakeFromMalloc
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500882
Kevin Lubickeda0b432019-12-02 08:26:48 -0500883 return CanvasKit._MakeImage(info, pptr, pixels.length, width * bytesPerPixel);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500884}
885
886CanvasKit.MakeLinearGradientShader = function(start, end, colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -0400887 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500888 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
889 flags = flags || 0;
890
891 if (localMatrix) {
892 // Add perspective args if not provided.
893 if (localMatrix.length === 6) {
894 localMatrix.push(0, 0, 1);
895 }
896 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
897 colors.length, mode, flags, localMatrix);
898 } else {
899 var lgs = CanvasKit._MakeLinearGradientShader(start, end, colorPtr, posPtr,
900 colors.length, mode, flags);
901 }
902
903 CanvasKit._free(colorPtr);
904 CanvasKit._free(posPtr);
905 return lgs;
906}
907
908CanvasKit.MakeRadialGradientShader = function(center, radius, colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -0400909 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500910 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
911 flags = flags || 0;
912
913 if (localMatrix) {
914 // Add perspective args if not provided.
915 if (localMatrix.length === 6) {
916 localMatrix.push(0, 0, 1);
917 }
918 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
919 colors.length, mode, flags, localMatrix);
920 } else {
921 var rgs = CanvasKit._MakeRadialGradientShader(center, radius, colorPtr, posPtr,
922 colors.length, mode, flags);
923 }
924
925 CanvasKit._free(colorPtr);
926 CanvasKit._free(posPtr);
927 return rgs;
928}
929
930CanvasKit.MakeTwoPointConicalGradientShader = function(start, startRadius, end, endRadius,
931 colors, pos, mode, localMatrix, flags) {
Kevin Lubickee91c072019-03-29 10:39:52 -0400932 var colorPtr = copy1dArray(colors, CanvasKit.HEAPU32);
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500933 var posPtr = copy1dArray(pos, CanvasKit.HEAPF32);
934 flags = flags || 0;
935
936 if (localMatrix) {
937 // Add perspective args if not provided.
938 if (localMatrix.length === 6) {
939 localMatrix.push(0, 0, 1);
940 }
941 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
942 start, startRadius, end, endRadius,
943 colorPtr, posPtr, colors.length, mode, flags, localMatrix);
944 } else {
945 var rgs = CanvasKit._MakeTwoPointConicalGradientShader(
946 start, startRadius, end, endRadius,
947 colorPtr, posPtr, colors.length, mode, flags);
948 }
949
950 CanvasKit._free(colorPtr);
951 CanvasKit._free(posPtr);
952 return rgs;
953}
954
955CanvasKit.MakeSkVertices = function(mode, positions, textureCoordinates, colors,
Kevin Lubickb3574c92019-03-06 08:25:36 -0500956 boneIndices, boneWeights, indices, isVolatile) {
Kevin Lubickb3574c92019-03-06 08:25:36 -0500957 // Default isVolitile to true if not set
958 isVolatile = isVolatile === undefined ? true : isVolatile;
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400959 var idxCount = (indices && indices.length) || 0;
960
961 var flags = 0;
962 // These flags are from SkVertices.h and should be kept in sync with those.
963 if (textureCoordinates && textureCoordinates.length) {
964 flags |= (1 << 0);
965 }
966 if (colors && colors.length) {
967 flags |= (1 << 1);
968 }
969 if (boneIndices && boneIndices.length) {
970 flags |= (1 << 2);
971 }
972 if (!isVolatile) {
973 flags |= (1 << 3);
974 }
975
976 var builder = new CanvasKit._SkVerticesBuilder(mode, positions.length, idxCount, flags);
977
978 copy2dArray(positions, CanvasKit.HEAPF32, builder.positions());
979 if (builder.texCoords()) {
980 copy2dArray(textureCoordinates, CanvasKit.HEAPF32, builder.texCoords());
981 }
982 if (builder.colors()) {
983 copy1dArray(colors, CanvasKit.HEAPU32, builder.colors());
984 }
985 if (builder.boneIndices()) {
986 copy2dArray(boneIndices, CanvasKit.HEAP32, builder.boneIndices());
987 }
988 if (builder.boneWeights()) {
989 copy2dArray(boneWeights, CanvasKit.HEAPF32, builder.boneWeights());
990 }
991 if (builder.indices()) {
992 copy1dArray(indices, CanvasKit.HEAPU16, builder.indices());
993 }
Kevin Lubickb3574c92019-03-06 08:25:36 -0500994
Kevin Lubickf5ea37f2019-02-28 10:06:18 -0500995 var idxCount = (indices && indices.length) || 0;
Kevin Lubickd6ba7252019-06-03 14:38:05 -0400996 // Create the vertices, which owns the memory that the builder had allocated.
997 return builder.detach();
Kevin Lubicka4f218d2020-01-14 08:39:09 -0500998};