为什么fillStyle未定义?

问题描述:

处理绘制到html 5画布的角度2项目。其主要功能是,用户的鼠标位置被绘制到屏幕上,慢慢地消失(被由半透明的矩形覆盖了)为什么fillStyle未定义?

现在,当我运行该脚本,我得到这个错误:

Cannot set property 'fillStyle' of undefined

我究竟做错了什么?

interface mouseInterface { 
    previousX: number; 
    previousY: number; 
} 

import {Injectable} from '@angular/core'; 

@Injectable() 
export class CanvasService { 

    context: CanvasRenderingContext2D; 
    canvas: any = null; 

    init(canvas) { 
    this.canvas = canvas; 
    this.canvas.width = window.innerWidth; 
    this.canvas.height = window.innerHeight; 
    this.canvas.style = 'border:solid 1px red;' 
    this.context = canvas.getContext("2d"); 
    this.fadeOut(); 

    } 

    fadeOut() { 
    let ctx = this.context; 
    ctx.fillStyle = "rgba(255,255,255,.2)"; 
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); 
    setTimeout(this.fadeOut, 100); 
    } 

    draw(data) { 
    //does drawing behavior based on mouse position 
    } 

} 
+1

要澄清,'fillStyle'不是未定义的,'ctx'是。 – CollinD

+0

你确定init方法在fadeOut之前被调用吗? – Polochon

随着代码,我可以在这里看到你的init()不会被调用。

  1. 名称的方法:ngOnInit()

  2. 添加工具的OnInit到:出口类CanvasService实现的OnInit

  3. 添加import语句的OnInit:进口{注射,OnInit中}
  4. 检查您的服务列在app.module.ts中的提供商列表中