JSFiddle - React, Tailwind, and code Playground
HTML
<div style="font-family:monospace">
x: <input type="text" id="sx" size="2" value="50" />
y: <input type="text" id="sy" size="2" value="50" /></br/>
w: <input type="text" id="sw" size="2" value="100" />
h: <input type="text" id="sh" size="2" value="100" /><br/>
<input type="file" id="fileinput" /><br/>
<canvas id="canvas" width="200" height="200"></canvas>
<br /><br />
<div id="output" style="width:200px; overflow-x:auto;"></div>
</div>
JavaScript
function drawCroppedImage(img, canvas, crop_x, crop_y, crop_width, crop_height) {
// trim the canvas
canvas.width = crop_width;
canvas.height = crop_height;
// draw the image with offset
var ctx = document.getElementById('canvas').getContext('2d');
ctx.drawImage(img, crop_x,crop_y,crop_width,crop_height, 0,0,crop_width,crop_height);
// output the base64 of the cropped image
document.getElementById('output').innerHTML = canvas.toDataURL() + "<br/><a href='" + canvas.toDataURL() + "'>Download</a>";
}
function cropLoadedImage(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image;
img.onload = function() {
// get input vars
var crop_height = document.getElementById('sw').value,
crop_width = document.getElementById('sh').value,
crop_x = document.getElementById('sx').value,
crop_y = document.getElementById('sy').value;
drawCroppedImage(img, document.getElementById('canvas'), crop_x,crop_y,crop_width,crop_height)
}
img.src = event.target.result;
}
reader.readAsDataURL(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', cropLoadedImage, false);