美文网首页
Angular中使用cropper

Angular中使用cropper

作者: 易澜湾 | 来源:发表于2018-12-05 17:31 被阅读0次

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

首先建立一个image Component

image.component.html文件如下

  <input type="file" class="js-uploadfile" id="image" (change)="select($event)">
  <!--确定裁剪-->
  <input type="button" class="js-ok" value="裁剪" (click)="cutImage()">
  <!--cropper基本结构-->
  <div class="container js-container" style="width: 100%;height: auto">
    <img id="js_image" class="js-image" src="" style="width: 100%;height: auto">
  </div>
  <!--裁剪结果显示-->
  <div style="width: 60%;height: auto;margin: 1rem 20%">
    <img id="showImg" src="" alt="" style="width: 100%;height: auto">
  </div>

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

      本文链接:https://www.haomeiwen.com/subject/tkywcqtx.html