简体   繁体   中英

How to fix "Cannot read property 'toDataURL' of undefined" in angular2-signaturePad

I am building a project that uses Angular 7. I am currently trying to implement signature and save the signature image in database. So I choose "angular2-signaturepad" package to implement the signature.It is working fine till the draw completes. After the completion of the signature draw I want to save the image. But it showing the error "Cannot read property 'toDataURL' of undefined" after the draw complete.

In html file

<signature-pad [options]='signaturePadOptions' (onBeginEvent)="drawBegin()" (onEndEvent)="drawComplete()"></signature-pad>

in ts file

import { SignaturePad } from "angular2-signaturepad/signature-pad";

inside oninit

  @ViewChild('SignaturePad') signaturePad: SignaturePad;
  public SignaturePadOptions = {
    'minWidth':2,
    'penColor':'rgb(66,133,244)',
    'backgroundColor':'rgb(255,255,255)',
    'canvasWidth':450,
    'canvasHeight':150,
  };
  public drawBegin(): void {
    console.log('Begin Drawing');
  }

  public drawComplete(): void {
    let signature = this.signaturePad.toDataURL('image/jpeg', 0.5);
    console.log(signature);
  }
}```



I expect the output should be the base url image name while console the result. But it is showing error "ERROR TypeError: Cannot read property 'toDataURL' of undefined".

I get such problem with ionic 4,because Ionic executes constructor before the view finishes to render. see this may it help https://github.com/szimek/signature_pad/issues/412

Found this in a comment from znotdead on another question: There is a signature pad for Angular that save it to image?

Change the import statement from:

   import { SignaturePad } from "angular2-signaturepad/signature-pad";

to

   import { SignaturePad } from 'angular2-signaturepad';

try add this

 ionViewDidEnter() {
   var canvas =document.querySelector('canvas');
   this.signaturePad = new SignaturePad(canvas);
  }
ngAfterViewInit() {
    setTimeout(() => {
      console.log('signature pad', this.signaturePad);
    }, 1000);
  }

It worked for me like this:

constructor(private elRef: ElementRef) {
}
ionViewDidEnter() {
    const canvas = this.elRef.nativeElement.querySelector('canvas');
    this.signaturePad = new SignaturePad(canvas);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM