2017-12-02 301 views
0

尝试在javascript中使用图像作为属性创建类时出现问题。我用context.drawImage注释的那一行会引发这个错误。在javassript中使用drawimage类中的未捕获类型错误

未捕获的类型错误:未能执行上“CanvasRenderingContext2D”“的drawImage”:所提供的值不是类型的“(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)”。

我觉得这很有趣,因为当我看着图像时,我在调试时作为参数传递,它告诉我它是一个HTMLImageElement。我来自静态类型的语言,我不明白为什么有一个类型错误,当传递的对象显然是错误所要求的类型。 `

 var canvas = document.getElementById('canvas'); 

     var context = canvas.getContext('2d'); 

     var edgeY = 600; 

     function Start() 
     { 
      var letter = new Letter(true, 10); 
     } 


     function Letter(_isSyllable, speed) 
     { 
      this.isSyllable = _isSyllable; 
      this.imgObject = new Image(80, 80); 
      this.posY = 10; 
      this.speed = speed; 
      this.ImageReady = false; 
      var source; 
      if (this.isSyllable) 
      { 
       source = "./Maganhangzok/image_part_" + (Math.floor(Math.random() * 14 + 1)) + ".jpg"; 
      } 
      else 
      { 
       source = "./Massalhangzok/image_part_" + (Math.floor(Math.random() * 20 + 1)) + ".jpg"; 
      } 
      this.imgObject.src = source;  
      this.imgObject.onLoad = new function() 
      { 
       this.ImageReady = true; 
       console.log(this.imgObject); 
       context.drawImage(this.imgObject, 120, this.posY); //this one throws the exception 
      } 


     } 
     Letter.prototype.Move = new function() 
     { 
      this.posY += this.speed; 
      context.clearRect(120, this.posY, 80, 80); 
      if (!this.ImageReady) 
      { 
       return false; 
      } 
      if (this.posY + 80 > edgeY) 
      { 
       return true; 
      } 
      else 
      { 
       context.drawImage(this.imgObject, 120, this.posY); 
       return false; 
      } 

     } 


    </script>` 
+0

你怎么称之为'onLoad'方法? (JS区分大小写,事件处理程序全部小写)。您的类型错误可能是由HTMLImage导致,但尚未加载有效的源代码。 – Kaiido

+0

我试过了,但函数调用的方式没有输入错误,但我开始单步调试函数,我注意到在onload的事件函数中,this.imgObject突然变成了未定义的,而在构造函数中它有一个值。事件发生时,它为什么会失去它的价值? – Mugiwara

+0

由于事件处理程序默认绑定到触发事件的元素。你将不得不调用这个函数的'bind()'方法。 – Kaiido

回答

0

您需要首先调用的onLoad和设置源URL。

this.imgObject.onLoad = new function() 
    { 
     this.ImageReady = true; 
     console.log(this.imgObject); 
     context.drawImage(this.imgObject, 120, this.posY); //this one throws the exception 
    } 
    this.imgObject.src = source;