Angular中使用cropper

最近做H5图片拍照裁剪上传的功能,网上找了教程。但是是jquery写的,移植到Angualr的Ts文件上出现了各种问题,最后一一修复了。贴在这里,希望能帮到大家。
我用的裁剪工具是cropper

首先建立一个image Component

image.component.html文件如下

  
  
  
  
  

image.component.ts文件如下

  import {Component, OnInit, ElementRef} from '@angular/core';
  import Cropper from 'cropperjs';

  @Component({
    selector: 'app-image',
    templateUrl: './image.component.html',
    styleUrls: ['./image.component.css']
  })
  export class ImageComponent implements OnInit {

    image: any;
    cropper: any;
    constructor(private el: ElementRef) {
    }

    ngOnInit() {
      this.image = this.el.nativeElement.querySelector('#js_image');
    }

    select($event) {
      const fr = new FileReader();
      const file = $event.path[0].files[0];
      fr.readAsDataURL(file);
      const _this = this;
      fr.onload = function () {
        _this.image['setAttribute']('src', fr.result);
        _this.iniCropper();
      };
    }

    iniCropper() {
       this.cropper = new Cropper(this.image, {
        aspectRatio: 16 / 9,
        crop(event) {
          console.log(event.detail.x);
          console.log(event.detail.y);
          console.log(event.detail.width);
          console.log(event.detail.height);
          console.log(event.detail.rotate);
          console.log(event.detail.scaleX);
          console.log(event.detail.scaleY);
        },
      });
    }

    cutImage() {
      const dataURL = this.image.cropper['getCroppedCanvas']('', {width: 200, height: 200});
      const data = {
        imgData: dataURL.toDataURL('image/png')
      };
     console.log(data);
      // 提交数据
      // submit(url, data);
    }
  }

采坑纪实:

html因为都是统一的,并没有什么坑,关键是ts文件
坑一:获取html中的节点不能用document.getElementById ,angular中先加载ts文件,再加载view,所以获取不到节点。 需要用angualr提供的ElementRef来获取节点,如下所示:

  this.el.nativeElement.querySelector('#js_image');

坑二:onchage事件触发后获取这个this,在angualr中,onchage事件写作 (change),当此事件触发后,不能用this来获取这个节点的内容,应该用$event,如下:

  const file = $event.path[0].files[0];

坑三:ts中很多方法不能通过 . 的形式调用,比如

 image.setAttribute.('src', fr.result)  

要写成如下格式

 image['setAttribute']('src', fr.result);

同理

  this.image.cropper('getCroppedCanvas', {width: 200, height: 200});

要写成:

  this.image.cropper['getCroppedCanvas']('', {width: 200, height: 200});

你可能感兴趣的:(Angular中使用cropper)