blob: e49d2b78ba80085614bf28e8e6e14b410de5267d [file] [log] [blame]
Kevin Lubick217056c2018-09-20 17:39:31 -04001
Kevin Lubick1a05fce2018-11-20 12:51:16 -05002// Adds any extra JS functions/helpers we want to add to CanvasKit.
Kevin Lubick217056c2018-09-20 17:39:31 -04003// Wrapped in a function to avoid leaking global variables.
4(function(CanvasKit){
5
6 function clamp(c) {
7 return Math.round(Math.max(0, Math.min(c || 0, 255)));
8 }
9
10 // Colors are just a 32 bit number with 8 bits each of a, r, g, b
11 // The API is the same as CSS's representation of color rgba(), that is
12 // r,g,b are 0-255, and a is 0.0 to 1.0.
Kevin Lubick1a05fce2018-11-20 12:51:16 -050013 // if a is omitted, it will be assumed to be 1.0
Kevin Lubick217056c2018-09-20 17:39:31 -040014 CanvasKit.Color = function(r, g, b, a) {
Kevin Lubick1a05fce2018-11-20 12:51:16 -050015 if (a === undefined) {
16 a = 1;
17 }
Kevin Lubick217056c2018-09-20 17:39:31 -040018 return (clamp(a*255) << 24) | (clamp(r) << 16) | (clamp(g) << 8) | (clamp(b) << 0);
19 }
Kevin Lubick61ef7b22018-11-27 13:26:59 -050020
21 // returns [r, g, b, a] from a color
22 // where a is scaled between 0 and 1.0
23 CanvasKit.getColorComponents = function(color) {
24 return [
25 (color >> 16) & 0xFF,
26 (color >> 8) & 0xFF,
27 (color >> 0) & 0xFF,
28 ((color >> 24) & 0xFF) / 255,
29 ]
30 }
Kevin Lubick12c0e502018-11-28 12:51:56 -050031
32 CanvasKit.multiplyByAlpha = function(color, alpha) {
33 if (alpha === 1) {
34 return color;
35 }
36 // extract as int from 0 to 255
37 var a = (color >> 24) & 0xFF;
38 a *= alpha;
39 // mask off the old alpha
40 color &= 0xFFFFFF;
41 return clamp(a) << 24 | color;
42
43 }
Kevin Lubick6fccc9d2018-11-20 15:55:10 -050044}(Module)); // When this file is loaded in, the high level object is "Module";
Kevin Lubick12c0e502018-11-28 12:51:56 -050045
46// See https://stackoverflow.com/a/31090240
47// This contraption keeps closure from minifying away the check
48// if btoa is defined *and* prevents runtime "btoa" or "window" is not defined.
49// Defined outside any scopes to make it available in all files.
50var isNode = !(new Function("try {return this===window;}catch(e){ return false;}")());
Kevin Lubick1646e7d2018-12-07 13:03:08 -050051
52function almostEqual(floata, floatb) {
53 return Math.abs(floata - floatb) < 0.00001;
54}