cropping tool for images js code example
Example: crop image javascript
Here is a function to get the image as you are uploading using the choose file button
function readURL() {
const myimg = document.getElementById("myimg");
const input = document.getElementById("myfile");
if(input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = e => {
console.log("changed");
myimg.src = e.target.result;
};
reader.readAsDataURL(input.files[0]);
}
}
document.querySelector('#myfile').addEventListener('change', () => {
readURL();
});
And the HTML will be
<img src="" id="myimg"><br>
<input type="file" id="myfile">
Here is a working fiddle
If you add a file the preview image will be updated. You actually get a data url here. Use the data url to the load the image to the canvas then crop it. calling drawimg(e.target.result)
function drawimg(idata) {
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 33, 71, 104, 124, 21, 20, 87, 104);
};
img.src = idata;
}