Crop the image using JavaScript

In my Angular 6 application I am making a file upload option and in preview the uploaded file needs to be displayed with auto cropping and auto resizing.

I have tried the following,

HTML:

<canvas id="canvas"></canvas>
<div style="display:none;">
  <img id="source" [src]="url" width="300" height="227">
</div>
<input type='file' (change)="onSelectFile($event)">

File select functtion:

  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }

      const canvas : any =  document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      const image = document.getElementById('source');

      ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
    }
  }

In the above I have tried the following with the reference of link https://jsfiddle.net/8jwq3cs7/

      const canvas : any =  document.getElementById('canvas');
      const ctx = canvas.getContext('2d');
      const image = document.getElementById('source');

      ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);

Before using the canvas the original image looks like this: https://mdn.mozillademos.org/files/5397/rhino.jpg

Whereas after using canvas it’s like this: https://jsfiddle.net/8jwq3cs7/

But if I choose the image from choose file then I am unable to see the image after choosing…

Working example: https://stackblitz.com/edit/angular-file-upload-preview-uwpf8f

Even the solution with pure JavaScript alone would also be appreciable if not in the Angular way…

The requirement is, if I choose a file then the same file needs to be cropped and fit the size automatically in preview…

Kindly help me to achieve the result without jQuery or any library

Leave a Comment