Angular 6 - 无法在画布上动态添加文本 [英] Angular 6 - Not able to add text on canvas dynamically

查看:28
本文介绍了Angular 6 - 无法在画布上动态添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created canvas element. Once user add some text with the help of keyboard, on click of done button I want to add text on canvas. I did below changes

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 函数将在点击键盘的完成按钮时调用.我没有收到任何错误,但无法在画布上看到文本.

SendMessage function will get call on click of done button of keyboard. I am not getting any error but not able to see text on canvas.

推荐答案

在纯 JS 实现中,您的代码运行良好:

In a pure JS implementation your code works fine:

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;
那一定不是得到正确的画布

The only issue that I could see is the:
this.canvasElement = this.canvas.nativeElement;
That must not be getting the correct canvas

这篇关于Angular 6 - 无法在画布上动态添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆