summaryrefslogtreecommitdiff
path: root/main.js
blob: 0fde2835f7ccee606d67464f0fff3f9f79cbcb33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
let canvas;
let video;
let ctx;
let settings = {
  "brightness": {},
  "saturate": {},
  "contrast": {},
  "hue-rotate": {filter: value => value + "deg"},
  "grayscale": {},
  "sepia": {},
  "invert": {},
  "blur": { filter: value => value * canvas.width / 100 + 'px' }
};
const img = new Image();
let lensflare_active = false;
let cursor = {
  x: 0,
  y: 0
};

// wait for site to be parsed so element can be found
document.addEventListener("DOMContentLoaded", function() {
  canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext("2d");
  video = document.getElementById("video");
  document.getElementById("back").addEventListener("click", () => document.body.className = "import-active");

  // bind listeners
  document.getElementById("viewport").addEventListener("drop", drop_handler);
  document.getElementById("viewport").addEventListener("dragover", event => event.preventDefault());
  document.getElementById("take-picture").addEventListener("click", use_camera);
  document.getElementById("cheese").addEventListener("click", take_picture);
  document.getElementById("upload-image").addEventListener("change", upload_image)

  for (let element of document.getElementsByClassName("save-image")) {
    element.addEventListener("click", save_image)
  }
  for (let element of document.getElementsByClassName("share-image")) {
    element.addEventListener("click", share_image)
  }

  for (let element of document.getElementsByClassName("lensflare")) {
    element.addEventListener("click", function(event) {
      event.preventDefault();
      lensflare_active = !lensflare_active;
      if (lensflare_active) {
        event.target.classList.add("is-primary");
      } else {
        event.target.classList.remove("is-primary");
      }
      draw(true);
    });
  }

  document.getElementById("viewport").addEventListener("mousemove", function(event) {
    if (event.buttons === 1 && lensflare_active) {
      cursor.x = (event.clientX - canvas.offsetLeft) / canvas.clientWidth - 0.5;
      cursor.y = (event.clientY - canvas.offsetTop) / canvas.clientWidth - 0.5;
      console.log(cursor);
      draw(true);
    }
  });

  window.addEventListener("deviceorientation", function(event) {
    if (lensflare_active) {
      cursor.x = event.gamma / 360 * 4;
      cursor.y = (event.beta - 90) / 360 * 4;
      console.log(cursor);
      // draw(true);
    }
  });

  function animation() {
    if (lensflare_active) {
      draw(true);
    }
    requestAnimationFrame(animation)
  };
  animation();

  window.addEventListener("resize", () => draw(true))

  video.addEventListener("canplay", function() {
    const width = 320;
    let height = video.videoHeight / (video.videoWidth / width);

    // Firefox currently has a bug where the height can't be read from
    // the video, so we will make assumptions if this happens.

      if (isNaN(height)) {
        height = width / (4 / 3);
      }
    video.width = width;
    video.height = height;
  });

  for (let setting in settings) {
    // make an array out of an iterable
    const elements = [...document.getElementsByClassName(setting)];
    settings[setting].elements = elements;
    // if filter is not definded, use identity function
    settings[setting].filter ||= value => value;
    for (let element of elements) {
      element.addEventListener("input", settings_apply);
    }

    const reset_elements = document.getElementsByClassName(setting + "-reset");
    for (let reset_element of reset_elements) {
      reset_element.addEventListener("click", () => reset_all(setting));
    }
  }
});

function reset_all(setting) {
  console.log("reseting " + setting);
  for (let element of settings[setting].elements) {
    element.value = element.defaultValue;
  }
  draw(true);
}

function use_camera() {
  navigator.mediaDevices
    .getUserMedia({ video: true, audio: false })
    .then((stream) => {
      video.srcObject = stream;
      video.play();
      document.body.className = "camera-active";
    })
    .catch((err) => {
      console.error(`An error occurred: ${err}`);
    });
}

function take_picture() {
  canvas.width = video.width;
  canvas.height = video.height;
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  img.src = canvas.toDataURL("image/png");
  img.onload = () => draw(true);

  document.body.className = "editor-active";
}

function upload_image() {
  document.body.className = "editor-active";

  console.log(this.files[0]);

  img.src = URL.createObjectURL(this.files[0]);
  img.onload = () => draw(true);
}

// https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop
function drop_handler(ev) {
  ev.preventDefault();
  let file;

  if (ev.dataTransfer.items) {
    const item = ev.dataTransfer.items[0];
    if (item.kind !== "file") return;
    file = item.getAsFile();
  } else {
    file = ev.dataTransfer.files[0];
  }
  console.log(file);

  document.body.className = "editor-active";
  img.src = URL.createObjectURL(file);
  img.onload = () => draw(true);
}

function save_image(event) {
  event.preventDefault();
  draw(false);

  const dataUrl = canvas.toDataURL("image/png");
  // downloading only works with links but not window.open
  const link = document.createElement('a');
  link.href = dataUrl;
  link.download = 'imagine.png';
  link.click();
}

function share_image(event) {
  event.preventDefault();
  if (!navigator.share) {
    console.log("navigator.share does not exist");
    return;
  }

  canvas.toBlob(async (blob) => {
    if (!blob) return;
    const file = new File([blob], 'imagine.png', {type: 'image/png'});

    try {
      await navigator.share({files: [file]});
    } catch (error) {
      console.log('Error sharing:', error);
    }
  }, 'image/png');
}

function settings_apply(event) {
  const changed_setting = event.target.id;
  const new_value = event.target.value;

  // update all inputs for that setting (mobile and desktop) to the new value
  for (let element of settings[changed_setting].elements) {
    if (element == event.target) continue;
    element.value = new_value;
  }

  draw(true);
}

// https://www.shadertoy.com/view/ldSXWK
function lensflare(pos_x, pos_y) {
  const imgdata = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const pixel_count = imgdata.data.length / 4;
  const aspect_ratio = canvas.width / canvas.height;
  for (let i = 0; i < pixel_count; i++) {
    const x = i % canvas.width;
    const y = i / canvas.width;
    const u = (x / canvas.width - .5) * aspect_ratio;
    const v = y / canvas.height - .5;

    const intensity = 1.5 * 255;
    const uv_len = u * u + v * v;
    const uvd_x = u * uv_len;
    const uvd_y = v * uv_len;
    const uvd_len = uvd_x * uvd_x + uvd_y * uvd_y;

    const uvd_pos_x = uvd_x + pos_x;
    const uvd_pos_y = uvd_y + pos_y;
    let temp = uvd_pos_x * uvd_pos_x + uvd_pos_y * uvd_pos_y
    const f2 = Math.max(1.0 / (1.0 + 32.0 * temp * .64), .0) * 0.1;
    const f22 = Math.max(1.0 / (1.0 + 32.0 * temp * .72), .0) * 0.08;
    const f23 = Math.max(1.0 / (1.0 + 32.0 * temp * .81), .0) * 0.06;

    let uvx_x = u * (1 + 0.5) + uvd_x * 0.5;
    let uvx_y = v * (1 + 0.5) + uvd_y * 0.5;
    let uvx_pos_x = uvx_x + pos_x;
    let uvx_pos_y = uvx_y + pos_y;

    temp = uvx_pos_x * uvx_pos_x + uvx_pos_y * uvx_pos_y
    const f4 = Math.max(0.01 - temp * .16, .0) * 6.0;
    const f42 = Math.max(0.01 - temp * .20, .0) * 5.0;
    const f43 = Math.max(0.01 - temp * .25, .0) * 3.0;

    uvx_x = u * (1 + 0.4) + uvd_x * 0.4;
    uvx_y = v * (1 + 0.4) + uvd_y * 0.4;
    uvx_pos_x = uvx_x + pos_x;
    uvx_pos_y = uvx_y + pos_y;

    temp = uvx_pos_x * uvx_pos_x + uvx_pos_y * uvx_pos_y
    const f5 = Math.max(0.01 - temp * .04, .0) * 2.0;
    const f52 = Math.max(0.01 - temp * .16, .0) * 2.0;
    const f53 = Math.max(0.01 - temp * .36, .0) * 2.0;

    uvx_x = u * (1 + 0.5) + uvd_x * 0.5;
    uvx_y = v * (1 + 0.5) + uvd_y * 0.5;
    uvx_pos_x = uvx_x - pos_x;
    uvx_pos_y = uvx_y - pos_y;

    temp = uvx_pos_x * uvx_pos_x + uvx_pos_y * uvx_pos_y
    const f6 = Math.max(0.01 - temp * .9, .0) * 6.0;
    const f62 = Math.max(0.01 - temp * .1, .0) * 3.0;
    const f63 = Math.max(0.01 - temp * .12, .0) * 5.0;

    imgdata.data[4 * i + 0] += 1.2 * ((f2 + f4 + f5 + f6) * 1.3 - uvd_len * .05) * intensity;
    imgdata.data[4 * i + 1] += 1.5 * ((f22 + f42 + f52 + f62) * 1.3 - uvd_len * .05) * intensity;
    imgdata.data[4 * i + 2] += 1.3 * ((f23 + f43 + f53 + f63) * 1.3 - uvd_len * .05) * intensity;
    imgdata.data[4 * i + 3] = 255;
  }
  ctx.putImageData(imgdata, 0, 0);
}

function draw(viewport_scale) {
  const filter = Object.entries(settings)
    .map(([setting, { elements, filter }]) => `${setting}(${filter(elements[0].value)})`)
    .join(" ")

  // set the resolution to the original and then scale down to the viewport to
  // only calculate the filter on pixels the user can see. 
  canvas.height = img.naturalHeight;
  canvas.width = img.naturalWidth;
  if (viewport_scale) {
    canvas.height = canvas.clientHeight;
    canvas.width = canvas.clientWidth;
  }
  ctx.filter = filter
  console.log(filter);
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  ctx.filter = '';

  if (lensflare_active) {
    lensflare(cursor.x, cursor.y);
  }
}