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