如何在图像上绘制 Angular2 Ionic2

How to Draw on Image Angular2 Ionic2

我知道如何在 Angular1 Ionic1 中绘图。

在我的html:

<img ng-src="{{image}}" style="width: 100%">
<canvas id="tempCanvas"></canvas>

在我的控制器中

var startimg="img/face.jpg";
$scope.image=startimg;

var canvas = document.getElementById('tempCanvas');
var context = canvas.getContext('2d');

var source =  new Image();
source.src = startimg;

canvas.width = source.width;
canvas.height = source.height;

console.log(canvas);

context.drawImage(source,0,0);

context.font = "100px impact";

textWidth = context.measureText($scope.frase).width;
if (textWidth > canvas.offsetWidth) {
    context.font = "40px impact";
}

context.textAlign = 'center';
context.fillStyle = 'white';             
context.fillText('HELLO WORLD',canvas.width/2,canvas.height*0.8);

var imgURI = canvas.toDataURL();

$timeout( function(){
    $scope.image = imgURI;
}, 200);

这段代码肯定会在面部图像的顶部绘制 HELLO WORLD 文本。

然而,在Ionic2/Angular2中,它似乎不起作用。我什至无法让 document.getElementById('tempCanvas') 工作。

请帮忙。

谢谢。

你可以这样写:

@Component({
  selector: 'my-app',
  template: `<h1>Angular 2 Systemjs start</h1>
    <img [src]="image">
   <canvas #layout></canvas>
  `
})    
export class App {
  @ViewChild('layout') canvasRef;
  image = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
  ngAfterViewInit() {
    let canvas = this.canvasRef.nativeElement;
    let context = canvas.getContext('2d');

    let source = new Image(); 
    source.crossOrigin = 'Anonymous';
    source.onload = () => {
        canvas.height = source.height;
        canvas.width = source.width;
        context.drawImage(source, 0, 0);

        context.font = "100px impact";
        context.textAlign = 'center';
        context.fillStyle = 'black';
        context.fillText('HELLO WORLD', canvas.width / 2, canvas.height * 0.8);

        this.image = canvas.toDataURL();  
    };
    source.src = this.image;
  }
}

另见 plunkr https://plnkr.co/edit/qAGyQVqbo3IGSFzC0DcQ?p=preview

或者您可以像这样使用自定义指令:

@Directive({
 selector: '[draw-text]' 
})
class ImageDrawTextDirective {
  loaded = false;
  @Input() text: String;
  @HostListener('load', ['$event.target'])
  onLoad(img) {
    if(this.loaded) {
      return;
    }
    this.loaded = true;
    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 = "100px impact";
    context.textAlign = 'center';
    context.fillStyle = 'black';
    context.fillText(this.text, canvas.width / 2, canvas.height * 0.8);

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

请参阅此案例的 plunkr https://plnkr.co/edit/BrbAoBlLcbDcx8iDXACv?p=preview