使用JavaScript裁剪图像

Man*_*gan 5 html javascript css html5-canvas angular

在我的Angular 6应用程序中,我正在选择文件上传选项,在预览中,需要使用自动裁剪和自动调整大小来显示上传的文件。

我尝试了以下方法

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)">
Run Code Online (Sandbox Code Playgroud)

文件选择功能:

  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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

在上面,我已经尝试通过链接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);
Run Code Online (Sandbox Code Playgroud)

在使用画布之前,原始图像如下所示:https : //mdn.mozillademos.org/files/5397/rhino.jpg

而使用画布后,就像这样:https : //jsfiddle.net/8jwq3cs7/

但是,如果我从中选择图片,choose file那么选择后我将看不到图片 ...

工作示例: https : //stackblitz.com/edit/angular-file-upload-preview-uwpf8f

即使不是以Angular的方式,即使仅使用纯JavaScript的解决方案也将是可观的...

要求是,如果我选择一个文件,则需要裁剪相同的文件并在预览中自动调整大小...

请帮助我在没有jQuery或任何库的情况下实现结果...

Geo*_*rge 11

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();
});
Run Code Online (Sandbox Code Playgroud)

And the HTML will be

<img src="" id="myimg"><br>
<input type="file" id="myfile">
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

See working Fiddle: here