Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created August 19, 2016 18:54
Show Gist options
  • Save allenhwkim/db78a2d5a2ded56308cca22bafff67d3 to your computer and use it in GitHub Desktop.
Save allenhwkim/db78a2d5a2ded56308cca22bafff67d3 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script>
var previewFile;
window.onload = function() {
var canvas = document.querySelector("#canvas-to-resize");
var ctx = canvas.getContext("2d");
var img = new Image();
var imgEl = document.querySelector('#image-resized');
var dataEl = document.querySelector('#image-data');
previewFile = function(event) {
var file = event.target.files[0];
var reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
}
reader.addEventListener("load", function (event) {
img.src = event.target.result;
}, false);
img.onload = function(event) {
var size = Math.min(img.width,img.height);
var x = (img.width - size) /2;
var y = (img.height - size) /2;
alert(`xxx ${img.width}, ${img.height}, ${x}, ${y}, ${size}`);
ctx.drawImage(img,x,y,size,size,0,0,256,256); // Or at whatever offset you like
alert(2);
imgEl.src = canvas.toDataURL('image/png');
alert(3);
//dataEl.innerHTML = imgEl.src;
}
}
}
// http://stackoverflow.com/questions/4773966/drawing-an-image-from-a-data-url-to-a-canvas
</script>
<script src="script.js"></script>
</head>
<body>
<div style="display:none">
<input id="image-file" type="file" onchange="previewFile(event)"><br>
<canvas id="canvas-to-resize" width="256" height="256"></canvas>
</div>
<a href="javascript:void(0)"
onclick="document.getElementById('image-file').click()">Edit Photo</a>
<img id="image-resized" style="border-radius: 50%; height: 150px" />
<pre id="image-data" style="white-space:pre-wrap; word-wrap: break-word"></pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment