如何绘制图像Angular2 Ionic2

时间:2016-06-17 04:17:21

标签: javascript image canvas angular 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')工作。

请帮忙。

感谢。

1 个答案:

答案 0 :(得分:10)

您可以写下以下内容:

@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