Last active
June 5, 2019 04:10
-
-
Save torufurukawa/da528ea16ae40bb06d0d0f5e249a9b71 to your computer and use it in GitHub Desktop.
Image Uploader
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"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Image Uploader</title> | |
</head> | |
<body> | |
<canvas id="canvas" style="border: solid 1px #cccccc" width="400" height="300"></canvas> | |
<div class="upload"> | |
<input type="file" name="file" id="file"> | |
</div> | |
<script> | |
const canvas = document.querySelector('#canvas') | |
const file = document.querySelector('#file') | |
file.addEventListener('change', (e) => { | |
const fileData = e.target.files[0] | |
if (!fileData.type.match('image.*')) { | |
alert('Choose an image') | |
return | |
} | |
const reader = new FileReader() | |
reader.onload = () => { | |
const ctx = canvas.getContext('2d') | |
const img = new Image() | |
img.src = reader.result | |
img.onload = function () { | |
canvas.height = canvas.width * this.height / this.width | |
ctx.drawImage(img, 0, 0, canvas.width, canvas.height) | |
} | |
} | |
reader.readAsDataURL(fileData) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment