簡體   English   中英

如何在圖像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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM