• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  <style>
9    canvas {
10      border: 1px dashed black;
11      width: 400px;
12      height: 400px;
13    }
14    #original {
15      display:none;
16    }
17  </style>
18
19<body>
20   <input type=file name=file id=file @change=${ele._onFileChange}/>
21   <canvas id=original></canvas>
22
23   <canvas id=grey></canvas>
24
25  <script type="text/javascript" charset="utf-8">
26    function drawImageAndGreyscaleImg(img) {
27      const oCanvas = document.querySelector('#original');
28      oCanvas.width = img.width;
29      oCanvas.height = img.height;
30      const oCtx = oCanvas.getContext('2d');
31
32      oCtx.drawImage(img, 0, 0);
33
34      const pixels = oCtx.getImageData(0, 0, img.width, img.height).data;
35
36      const gCanvas = document.querySelector('#grey');
37      gCanvas.width = img.width;
38      gCanvas.height = img.height;
39      const gCtx = gCanvas.getContext('2d');
40
41      for (let y = 0; y < img.height; y++) {
42        for (let x = 0; x < img.width; x++) {
43          const offset = 4*(x + img.width*y)
44          const r = pixels[offset], g = pixels[offset + 1],
45                b = pixels[offset + 2], a = pixels[offset + 3];
46          const grey = a*(r + g + b)/3;
47          pixels[offset    ] = grey;
48          pixels[offset + 1] = grey;
49          pixels[offset + 2] = grey;
50        }
51      }
52
53      const greyData = new ImageData(pixels, img.width, img.height);
54
55      gCtx.putImageData(greyData, 0, 0);
56    }
57    document.querySelector('#file').addEventListener('change', (e) => {
58      const toLoad = e.target.files[0];
59      const reader = new FileReader();
60      reader.addEventListener('load', () => {
61        const b64dataURL = reader.result;
62
63        const img = new Image();
64        img.src = b64dataURL;
65        requestAnimationFrame( () => {
66          drawImageAndGreyscaleImg(img);
67        });
68
69      });
70      reader.addEventListener('error', () => {
71        console.error('Failed to load '+ toLoad.name);
72      });
73      reader.readAsDataURL(toLoad);
74    });
75  </script>
76<body>
77</html>
78