Skip to content

Instantly share code, notes, and snippets.

@zvodd
Created April 19, 2022 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zvodd/dc9b98fdc4ab98a678548de4e7c445e0 to your computer and use it in GitHub Desktop.
Save zvodd/dc9b98fdc4ab98a678548de4e7c445e0 to your computer and use it in GitHub Desktop.
Client Side JS - Image Upload to Canvas
<!DOCTYPE html>
<html><head>
<style>
.finfo-list{
list-style: none;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
flex-direction: row;
max-height: 80vh;
overflow-y: scroll;
overflow-x: hidden;
}
</style>
</head><body>
<label for="imageLoader">Select Image File</label>
<input
type="file"
id="imageLoader"
name="imageLoader"
accept="image/*"
multiple
style="display:none"/>
<br />
<ul id="fileList" class="finfo-list"></ul>
<script src="main.js"></script>
</body></html>
const elimageLoader = document.getElementById('imageLoader'),
elFileList = document.getElementById('fileList');
elimageLoader.addEventListener('change', handleFiles, false);
function handleFiles(e){
let filesMap={};
[...e.target.files].forEach((fileobj,count)=>{
const name = fileobj.name,
key = `ikey_${(count).toString()}_${name}`,
info = JSON.stringify(fblob_info(fileobj),null,2),
element = fragmentFromString(`
<li id="wrap_${key}">
<h5>${name}</h5>
<pre>${info}</pre>
<canvas id="${key}"></canvas>
</li>`)
filesMap[key]={fileobj, element};
})
elFileList.replaceChildren(...Object.values(filesMap).map(e=>e.element))
for (let key in filesMap){
console.log("set up load hook for",key)
let {fileobj} = filesMap[key];
let canvas = document.getElementById(key)
let ctx = canvas.getContext('2d');
let reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = ()=>{
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(fileobj);
}
}
function fblob_info(fobj){
const cprops = ["lastModified","lastModifiedDate","webkitRelativePath","size","type"]
let info = {};
for (const prop in fobj){
if (cprops.includes(prop)){
info[prop] = fobj[prop].toString()
}
}
return info;
}
function fragmentFromString(strHTML) {
return document.createRange().createContextualFragment(strHTML);
// var temp = document.createElement('template');
// temp.innerHTML = strHTML;
// return temp.content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment