Angular 6-无法在画布上动态添加文本

时间:2018-07-31 11:51:13

标签: javascript css3 canvas html5-canvas angular6

我已经创建了canvas元素。一旦用户借助键盘添加了一些文本,就单击完成按钮,我想在画布上添加文本。我做了以下更改

1。 image-home.html

<canvas  (drop)="drop(event)" (dragover)="allowDrop(event)" no-bounce width="400px" height="400" 
      (touchstart)='handleStart($event)' (touchmove)='handleMove($event)' 
      [ngStyle]="{'background': '#fff url(' + selectedImage + ') no-repeat 0 0', 'background-size' : 'contain',
      'background-position': 'center', 'background-size': '400px!important 400px!important'}" #canvas ></canvas>

2。 image-home.component.ts

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

@ViewChild('canvas') public canvas: ElementRef;

sendMessage(userData: string){
    console.log('entered text', userData);
    this.canvasElement = this.canvas.nativeElement;
    let ctx = this.canvasElement.getContext('2d');
    ctx.font = 'italic 18px Arial';
    ctx.textAlign = 'center';
    ctx. textBaseline = 'middle';
    ctx.fillStyle = 'red';  // a color name or by using rgb/rgba/hex values
    ctx.fillText('Hello World!', 150, 50); // text and position
    //this.canvasElement.fillText(userData, 10, 50);
    this.nativeKeyboard.hideMessenger(this.options);
  }

SendMessage函数将在单击键盘的完成按钮时得到调用。我没有收到任何错误,但无法在画布上看到文本。

2 个答案:

答案 0 :(得分:2)

在纯JS实现中,您的代码可以正常工作:

const canvas = document.getElementById('test');
canvas.width = canvas.height = 100;
ctx = canvas.getContext('2d');
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx. textBaseline = 'middle';
ctx.fillStyle = 'red';  
ctx.fillText('Hello!', 50, 50); 
  
<canvas id="test" style="border: 1px solid blue;" ></canvas>

我唯一看到的问题是:
this.canvasElement = this.canvas.nativeElement;
那一定不能得到正确的画布

答案 1 :(得分:0)

对于TypeScript /角度:

const canvas = <HTMLCanvasElement> document.getElementById('test');
ctx = canvas.getContext('2d');
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx. textBaseline = 'middle';
ctx.fillStyle = 'red';  
ctx.fillText('Hello!', 150, 50);