Created
April 26, 2019 05:19
-
-
Save codemilli/50807785bc3e37e8e15c8d045d65c614 to your computer and use it in GitHub Desktop.
canvas-resize
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> | |
canvas { | |
display: none; | |
} | |
#image { | |
max-width: 720px; | |
} | |
</style> | |
</head> | |
<body> | |
<div> | |
<img id="image" src="" alt=""> | |
<img id="resized" src="" alt=""> | |
</div> | |
<canvas id="canvas"></canvas> | |
<input id="file" type="file"/> | |
<script> | |
const canvas = document.getElementById('canvas'); | |
const file = document.getElementById('file'); | |
const image = document.getElementById('image'); | |
const resized = document.getElementById('resized'); | |
file.addEventListener('change', onChange); | |
function onChange(e) { | |
const file = e.target.files[0]; | |
const url = URL.createObjectURL(file); | |
image.onload = onLoad; | |
image.src = url; | |
} | |
function onLoad(e) { | |
const ctx = canvas.getContext('2d'); | |
const {naturalWidth: width, naturalHeight: height} = e.target; | |
const ratio = width / height; | |
const w = Math.min(width, 720); | |
const h = w / ratio; | |
canvas.width = w; | |
canvas.height = h; | |
ctx.drawImage(image, 0, 0, w, h); | |
resized.src = canvas.toDataURL(); | |
file.value = ''; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment