Kevin Lubick | 217056c | 2018-09-20 17:39:31 -0400 | [diff] [blame] | 1 | |
Kevin Lubick | 1a05fce | 2018-11-20 12:51:16 -0500 | [diff] [blame] | 2 | // Adds any extra JS functions/helpers we want to add to CanvasKit. |
Kevin Lubick | 217056c | 2018-09-20 17:39:31 -0400 | [diff] [blame] | 3 | // 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 Lubick | 1a05fce | 2018-11-20 12:51:16 -0500 | [diff] [blame] | 13 | // if a is omitted, it will be assumed to be 1.0 |
Kevin Lubick | 217056c | 2018-09-20 17:39:31 -0400 | [diff] [blame] | 14 | CanvasKit.Color = function(r, g, b, a) { |
Kevin Lubick | 1a05fce | 2018-11-20 12:51:16 -0500 | [diff] [blame] | 15 | if (a === undefined) { |
| 16 | a = 1; |
| 17 | } |
Kevin Lubick | 217056c | 2018-09-20 17:39:31 -0400 | [diff] [blame] | 18 | return (clamp(a*255) << 24) | (clamp(r) << 16) | (clamp(g) << 8) | (clamp(b) << 0); |
| 19 | } |
Kevin Lubick | 61ef7b2 | 2018-11-27 13:26:59 -0500 | [diff] [blame] | 20 | |
| 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 Lubick | 12c0e50 | 2018-11-28 12:51:56 -0500 | [diff] [blame] | 31 | |
| 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 Lubick | 6fccc9d | 2018-11-20 15:55:10 -0500 | [diff] [blame] | 44 | }(Module)); // When this file is loaded in, the high level object is "Module"; |
Kevin Lubick | 12c0e50 | 2018-11-28 12:51:56 -0500 | [diff] [blame] | 45 | |
| 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. |
| 50 | var isNode = !(new Function("try {return this===window;}catch(e){ return false;}")()); |
Kevin Lubick | 1646e7d | 2018-12-07 13:03:08 -0500 | [diff] [blame] | 51 | |
| 52 | function almostEqual(floata, floatb) { |
| 53 | return Math.abs(floata - floatb) < 0.00001; |
| 54 | } |