在angular 6的库中创建画布

时间:2019-04-23 09:02:25

标签: angular canvas

我正在尝试创建一个有角度的库,该库将允许我裁剪想要使用画布的图像。 我用“ ng generate library”创建一个库。 当我尝试绘制画布时,什么也没出现。

crop-image.component.html:

<div class="container">
  <canvas #canvas [width]="width" [height]="height" >
hello
  </canvas>
  <div>
    <input type="file" accept="/image/*" (change)="onImageChange($event)">
  </div>
</div>

crop-image.component.ts:

import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';

// @ts-ignore
@Component({
  selector: 'lib-crop-image',
  templateUrl: './crop-image.component.html',
  styleUrls: ['./crop-image.component.css']
})
export class CropImageComponent implements OnInit {


  imageUrl;
  @Input() width = 500;
  @Input() height = 500;
  @ViewChild('canvas') canvasRef: ElementRef;
  constructor() { }

  ngOnInit() {
    const ctx = this.canvasRef.nativeElement.getContext('2d');
    ctx.moveTo(0, 0);
    ctx.lineTo(100, 100);
    ctx.stroke();
}
 }

2 个答案:

答案 0 :(得分:0)

 ngOnInit() {
    const ctx = this.canvasRef.nativeElement.getContext('2d');
    ctx.moveTo(0, 0);
    ctx.lineTo(100, 100);
    ctx.stroke();
}

应该是

 ngAfterViewInit() {
    const ctx = this.canvasRef.nativeElement.getContext('2d');
    ctx.moveTo(0, 0);
    ctx.lineTo(100, 100);
    ctx.stroke();
}

答案 1 :(得分:0)

使用以下内容获取画布参考

import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';

// @ts-ignore
@Component({
  selector: 'lib-crop-image',
  templateUrl: './crop-image.component.html',
  styleUrls: ['./crop-image.component.css']
})
export class CropImageComponent implements OnInit, AfterViewInit  {


  imageUrl;
  @Input() width = 500;
  @Input() height = 500;
   @ViewChild('canvas') canvasRef: ElementRef;
  public context: CanvasRenderingContext2D;

  constructor() { }

  ngOnInit() {
}

  ngAfterViewInit(): void {
    this.context = (<HTMLCanvasElement>this.canvasRef.nativeElement).getContext(
      '2d');
    this.context.moveTo(0, 0);
    this.context.lineTo(100, 100);
    this.context.stroke();
  }
 }