1(function(window) { 2 3let CanvasKit = null; 4 5window.loadPolyfill = () => { 6 // TODO(kjlubick): change ready().then() to just then() when using a newer version 7 // from npm (see 8 // https://skia.googlesource.com/skia/+/d1285b131bcf9c10fe1ad16fd2830c556715ed9e) 9 return CanvasKitInit({ 10 locateFile: (file) => 'https://unpkg.com/canvaskit-wasm@0.6.0/bin/'+file, 11 }).ready().then((CK) => { 12 CanvasKit = CK; 13 }); 14} 15 16window.createImageData = (src, options) => { 17 const skImg = CanvasKit.MakeImageFromEncoded(src); 18 // we know width and height 19 const imageInfo = { 20 width: options.resizeWidth || skImg.width(), 21 height: options.resizeHeight || skImg.height(), 22 alphaType: options.premul ? CanvasKit.AlphaType.Premul : CanvasKit.AlphaType.Unpremul, 23 } 24 switch (options.colorType) { 25 case "float32": 26 imageInfo.colorType = CanvasKit.ColorType.RGBA_F32; 27 break; 28 29 case "uint8": 30 default: 31 imageInfo.colorType = CanvasKit.ColorType.RGBA_8888; 32 break; 33 } 34 35 const pixels = skImg.readPixels(imageInfo, 0, 0); 36 let output; 37 // ImageData at the moment only supports Uint8, so we have to convert our numbers to that 38 switch (options.colorType) { 39 case "float32": 40 // This will make an extra copy, which is a limitation of the native Browser's 41 // ImageData support. 42 output = new Uint8ClampedArray(pixels); 43 break; 44 45 case "uint8": 46 default: 47 // We can cast w/o another copy 48 output = new Uint8ClampedArray(pixels.buffer); 49 break; 50 } 51 52 53 const ret = new ImageData(output, imageInfo.width, imageInfo.height); 54 skImg.delete(); 55 56 return ret; 57} 58 59 60})(window); 61