2017-09-26 2 views
0

J'essaie de créer une classe qui dessine la carte et les caractères dans le canevas. Quand je rafraîchis la toile dans mon code, rien n'apparaît. Mais quand j'écris map.refresh() dans la console de développeur de Chrome, il apparaît juste. Voici mon code tapuscrit:Canvas ne dessine pas l'image dans le code, mais le fait dans la console du développeur

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(); 
    } 

} 

Et mon 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> 

Répondre

0

Cette ligne:

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

passera undefined à onload que la fonction est d'abord appelée, le le résultat de la fonction (undefined) est passé. Le rappel doit être référencé à la place.

Vous pouvez changer l'argument onload de prendre une définition de fonction, lier this à (sinon this représentera l'image elle-même) et appeler this.registerObject(this.img) de l'intérieur.