Skip to content

Instantly share code, notes, and snippets.

@codemilli
Created April 26, 2019 05:19
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 codemilli/50807785bc3e37e8e15c8d045d65c614 to your computer and use it in GitHub Desktop.
Save codemilli/50807785bc3e37e8e15c8d045d65c614 to your computer and use it in GitHub Desktop.
canvas-resize
<!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