Imagine/main.js

88 lines
2.3 KiB
JavaScript

let canvas;
let ctx;
let imports;
let settings = {
brightness: {},
saturate: {},
contrast: {},
blur: {prefix: 'px'}
};
const img = new Image();
// wait for site to be parsed so element can be found
document.addEventListener("DOMContentLoaded", function() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
imports = document.getElementById("imports");
// bind listeners
document.getElementById("take-picture").addEventListener("click", take_picture);
document.getElementById("upload-image").addEventListener("change", upload_image)
document.getElementById("save").addEventListener("click", save_image)
document.getElementById("share").addEventListener("click", share_image)
for (let setting in settings) {
// make an array out of an iterable
const elements = [...document.getElementsByClassName(setting)];
settings[setting].elements = elements;
for (let element of elements) {
element.addEventListener("input", settings_apply);
}
}
})
function take_picture() {
canvas.classList.remove("is-hidden");
imports.classList.add("is-hidden");
}
function upload_image() {
canvas.classList.remove("is-hidden");
imports.classList.add("is-hidden");
console.log(this.files[0]);
img.src = URL.createObjectURL(this.files[0]);
img.onload = function() {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
}
function save_image() {
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() {
}
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;
}
const filter = Object.entries(settings)
.map(([setting, {elements, prefix}]) => `${setting}(${elements[0].value}${prefix || ""})`)
.join(" ")
ctx.filter = filter
console.log(filter);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}