1<!DOCTYPE html>
2<html>
3<head>
4  <title>In-Browser Greyscale converter</title>
5  <meta charset="utf-8" />
6  <meta http-equiv="X-UA-Compatible" content="IE=edge">
7  <meta name="viewport" content="width=device-width, initial-scale=1.0">
8  <script src="https://unpkg.com/canvaskit-wasm@0.6.0/bin/canvaskit.js"></script>
9  <script type="text/javascript" src="/impl/impl.js"></script>
10  <style>
11    canvas {
12      border: 1px dashed black;
13      width: 400px;
14      height: 400px;
15    }
16    #original {
17      display:none;
18    }
19  </style>
20
21<body>
22   <input type=file name=file id=file @change=${ele._onFileChange}/>
23   <canvas id=original></canvas>
24
25   <canvas id=grey></canvas>
26
27  <script type="text/javascript" charset="utf-8">
28    loadPolyfill().then(() => {
29      function drawImageAndGreyscaleImg(imgData) {
30        const gCanvas = document.querySelector('#grey');
31        gCanvas.width = imgData.width;
32        gCanvas.height = imgData.height;
33        const gCtx = gCanvas.getContext('2d');
34
35        const pixels = imgData.data;
36
37        for (let y = 0; y < imgData.height; y++) {
38          for (let x = 0; x < imgData.width; x++) {
39            const offset = 4*(x + imgData.width*y)
40            const r = pixels[offset], g = pixels[offset + 1], b = pixels[offset + 2];
41            const grey = (r + g + b)/3;
42            pixels[offset    ] = grey;
43            pixels[offset + 1] = grey;
44            pixels[offset + 2] = grey;
45          }
46        }
47
48        const greyData = new ImageData(pixels, imgData.width, imgData.height);
49
50        gCtx.putImageData(greyData, 0, 0);
51      }
52      document.querySelector('#file').addEventListener('change', (e) => {
53        const blobToLoad = e.target.files[0];
54        // A browser implementation would be able to directly take the blob
55        const reader = new FileReader();
56        reader.addEventListener('load', () => {
57          const bytes = reader.result;
58          const imgData = window.createImageData(bytes, {
59            // Specify the destination properties, that is, what format to translate
60            // the pixels in the image to.
61            pixelWidth: "uint8",
62            premul: true,
63            colorSpace: "srgb",
64          });
65          requestAnimationFrame(() => {
66            drawImageAndGreyscaleImg(imgData);
67          });
68        });
69        reader.addEventListener('error', () => {
70          console.error('Failed to load '+ blobToLoad.name);
71        });
72        reader.readAsArrayBuffer(blobToLoad);
73      });
74    });
75
76  </script>
77<body>
78</html>
79