2016-11-09 97 views
0

處理繪製到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

回答

0

隨着代碼,我可以在這裏看到你的init()不會被調用。

  1. 名稱的方法:ngOnInit()

  2. 添加工具的OnInit到:出口類CanvasService實現的OnInit

  3. 添加import語句的OnInit:進口{注射,OnInit中}
  4. 檢查您的服務列在app.module.ts中的提供商列表中