Created
April 26, 2019 08:58
-
-
Save codemilli/c3654eeaee5e105bdbf3f0a560fc1dd0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Canvas</title> | |
<style> | |
body { font-size: 0 } | |
canvas { | |
display: none; | |
} | |
img { | |
max-width: 360px; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="wrap"></div> | |
<input id="file" type="file" multiple/> | |
<script> | |
const wrap = document.getElementById('wrap'); | |
const file = document.getElementById('file'); | |
file.addEventListener('change', onChange); | |
async function onChange(e) { | |
const files = e.target.files; | |
const resizedUrlList = await resizeImages(mapObjectUrl(files)); | |
resizedUrlList.forEach(({url, resizedUrl}) => { | |
const image = new Image(); | |
const resized = new Image(); | |
image.src = url; | |
resized.src = resizedUrl; | |
const row = document.createElement('div'); | |
row.appendChild(image); | |
row.appendChild(resized); | |
wrap.appendChild(row); | |
}); | |
file.value = ''; | |
} | |
function mapObjectUrl(files) { | |
const result = []; | |
for (let i = 0; i < files.length; i++) { | |
result[i] = URL.createObjectURL(files[i]); | |
} | |
return result; | |
} | |
function resizeImages(imageUrlList) { | |
return Promise.all(imageUrlList.map(async (url) => { | |
const image = await createImage(url); | |
const resizedUrl = getResizeImageUrl(image); | |
return { | |
url, | |
resizedUrl, | |
}; | |
})); | |
} | |
function createImage(url) { | |
return new Promise((resolve) => { | |
const image = new Image(); | |
image.onload = () => resolve(image); | |
image.src = url; | |
}); | |
} | |
function getResizeImageUrl(image) { | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
const {naturalWidth: width, naturalHeight: height} = image; | |
const ratio = width / height; | |
const w = Math.min(width, 360); | |
const h = w / ratio; | |
canvas.width = w; | |
canvas.height = h; | |
ctx.drawImage(image, 0, 0, w, h); | |
return canvas.toDataURL(); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment