Skip to content

Instantly share code, notes, and snippets.

@torufurukawa
Last active June 5, 2019 04:10
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 torufurukawa/da528ea16ae40bb06d0d0f5e249a9b71 to your computer and use it in GitHub Desktop.
Save torufurukawa/da528ea16ae40bb06d0d0f5e249a9b71 to your computer and use it in GitHub Desktop.
Image Uploader
<!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