html2canvas crop image code example

Example 1: crop image canvas

var image = new Image(),
    canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

image.src = 'https://i.stack.imgur.com/I4jXc.png';

image.onload = function(){
    ctx.drawImage(image,
        70, 20,   // Start at 70/20 pixels from the left and the top of the image (crop),
        50, 50,   // "Get" a `50 * 50` (w * h) area from the source image (crop),
        0, 0,     // Place the result at 0, 0 in the canvas,
        100, 100); // With as width / height: 100 * 100 (scale)
}

Example 2: 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;
}

Tags:

Java Example