Ionic2 camera image with canvas add text to that image

1.4k views Asked by At

In my ionic2 app I am trying to add text to the image I capture from camera. I have a directive for that:

@Directive({
 selector: '[draw-text]' 
})
export class ImageDrawTextDirective {
  @Input() text: any;
  @HostListener('load', ['$event.target'])
  onLoad(img) {
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');

    canvas.height = img.height;
    canvas.width = img.width;

    context.drawImage(img, 0, 0);
    context.font = "70px";
    context.textAlign = 'center';
    context.fillStyle = 'black';
    context.fillText(this.text, canvas.width / 2, canvas.height * 0.8);

    img.src = canvas.toDataURL();
  }
}

And page where I capture and show image:

<ion-item>
    <ion-label>Flaour</ion-label>
    <ion-select [(ngModel)]="flavour">
      <ion-option value="basilikum" selected="true">Basilikum</ion-option>
      <ion-option value="roast">Roast</ion-option>
    </ion-select>
</ion-item>
 <ion-card>
    <ion-card-content>


      <button ion-button (click)="takePicture()">
       <ion-icon name="camera"></ion-icon>
     </button>

     <img [src]="base64Image" *ngIf="base64Image" [text]="'HELLO'" draw-text crossOrigin style="background-repeat:no-repeat; background-position:center center;"/>
   </ion-card-content>


 </ion-card>

This successfully print HELLO on the captured image. But I would like to have the value selected from the select with [(ngModel)]="flavour". How can I achieve that?

I tried to replace HELLO with [text]="'{{flavour}}'" but it throws compilation error. What is the right way?

1

There are 1 answers

0
Thinker On

I updated [text]="'HELLO'" with text={{flavour}} and it worked.