blob: ce99cdd4b3f84c9db86f5d4cd4a17aef49334a84 [file] [log] [blame]
Kevin Lubick42daf992019-04-19 11:58:56 -04001<!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], b = pixels[offset + 2];
45 const grey = (r + g + b)/3;
46 pixels[offset ] = grey;
47 pixels[offset + 1] = grey;
48 pixels[offset + 2] = grey;
49 }
50 }
51
52 const greyData = new ImageData(pixels, img.width, img.height);
53
54 gCtx.putImageData(greyData, 0, 0);
55 }
56 document.querySelector('#file').addEventListener('change', (e) => {
57 const toLoad = e.target.files[0];
58 const reader = new FileReader();
59 reader.addEventListener('load', () => {
60 const b64dataURL = reader.result;
61
62 const img = new Image();
63 img.src = b64dataURL;
64 requestAnimationFrame( () => {
65 drawImageAndGreyscaleImg(img);
66 });
67
68 });
69 reader.addEventListener('error', () => {
70 console.error('Failed to load '+ toLoad.name);
71 });
72 reader.readAsDataURL(toLoad);
73 });
74 </script>
75<body>
76</html>