2017-09-26 4 views
0

캔버스에서지도와 문자를 그릴 클래스를 만들려고합니다. 내 코드에서 캔버스를 새로 고칠 때 아무 것도 나타나지 않습니다. 그러나 Chrome의 개발자 콘솔에서 map.refresh()를 작성하면 표시됩니다.Canvas가 코드에서 이미지를 그리지 않지만 개발자 콘솔에서 수행합니다.

class Map { 
    width:number = 800; 
    height:number = 600; 
    img:HTMLImageElement; 
    objectList = []; 

    constructor(img:string) { 

     var canvas = document.createElement("canvas"); 
     canvas.width = this.width; 
     canvas.height = this.height; 
     canvas.oncontextmenu = function() { return false; }; 
     document.body.appendChild(canvas); 

     var ctx = canvas.getContext("2d"); 
     if(!ctx) { 
      console.log("Canvas error"); 
     } 

     this.loadMap(img); 

    } 
    refresh() : any { 
     var canvas = document.querySelector("canvas"); 

     var ctx = canvas.getContext("2d"); 

     for(var i = 0; i < this.objectList.length; i++) { 
      var obj = this.objectList[i]; 
      ctx.drawImage(obj.img, 0, 0); 
     } 
    } 
    loadMap(img:string) { 
     this.img = new Image(); 
     this.img.src = img; 
     this.img.onload = <any> this.registerObject(this); 
    } 

    registerObject(obj:Object) { 
     this.objectList.push(obj); 
     this.refresh(); 
    } 

} 

그리고 내 index.html을 : 여기 내 타이프 라이터 코드의

<!DOCTYPE html> 
<html> 
    <head> 
     <style> 
      * { 
       margin: 0; 
       padding: 0; 
      } 
     </style> 
     <script src="map.js"></script> 
    </head> 
    <body> 

     <script> 
      var map = new Map("https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Worldmap_LandAndPolitical.jpg/1200px-Worldmap_LandAndPolitical.jpg"); 
     </script> 
    </body> 
</html> 

답변

0

이 줄 : 함수가 먼저 호출 될 때

this.img.onload = <any> this.registerObject(this); 
              ^^^^^^ (invokes function) 

그런 다음, onloadundefined을 전달합니다 기능 (undefined)의 결과가 전달됩니다. 대신 콜백을 참조해야합니다.

당신은 그것에 this을 결합, 함수 정의를 취할 onload에 인수를 변경할 수 있습니다 (그렇지 않으면 this는 이미지 자체를 나타냅니다)과 내부에서 this.registerObject(this.img)를 호출합니다.