2014-02-17 31 views
0

你好,stackoverflow社區!首先,我必須說,我沒有太多的構造函數經驗。 所以。我試圖做的是讓跳傘運動員從屏幕的頂部飛到底部。 我想我可以用一個構造函數來設置跳傘:用JavaScript構造函數動畫canvas

var parachute = function() { 
    this.height = 35; 
    this.width = 30; 
    this.speed = 50; 
    this.xPos = Math.round(Math.random() * (window.width - this.width)); 
    this.animate = function() { 
     this.img = new Image(); 
     this.yPos = 0; 
     this.img.onload = function() { 
      ctxPara.globalCompositeOperation = 'copy'; 
      ctxPara.translate(0, this.yPos); 
      ctxPara.drawImage(this.img, this.xPos, 0); 
     }; 
     this.img.src = 'para.png'; 
     this.yPos++; 
    }; 

};

此構造是在一個名爲「飛」功能使用:

var fly = function() {  
    var newParachute = new parachute(); 
    setInterval(newParachute.animate, newParachute.speed); 
}; 

而這個「飛」功能時觸發窗口負載:

​​

你應該看到什麼,是跳傘者飛過屏幕。但不幸的是,你不... 現在,之後,龍文。 (Iam非常抱歉,這麼長時間:-()我的問題是:你知道我做錯了嗎?我的構造器是否正確?是,我正在嘗試做什麼,應該是這樣寫的嗎?任何建議或對於一個成功的機會的建議?(我希望我的英語不是那麼糟糕,我認爲它是:-))

哦,我忘了提及錯誤。這是一個TypeMissMatchError。 這意味着「this.img」不是在這條線img元素:

ctxPara.drawImage(this.img, this.xPos, 0); 

現在,我跟着MARKE的例子。 而不是向我展示一個跳傘運動員。它顯示了我在這一行中的錯誤:ctxPara.drawImage(this.img,this.xPos,this.yPos);

var fly = function() { 
    var newParachute = new parachute(); 
    newParachute.img.load.call(newParachute); 
    setInterval(newParachute.animate.call(newParachute), newParachute.speed); 
}; 
var parachute = function() { 
    this.height = 35; 
    this.width = 30; 
    this.speed = 25; 
    this.xPos = Math.round(Math.random() * (window.innerWidth - this.width)); 
    this.img = new Image(); 
    this.yPos = 0; 
    this.img.isLoaded = false; 
    this.img.load = function() { 
     this.img.isLoaded = true; 
    }; 
    this.img.src = 'parachute.png'; 
    this.animate = function() { 
     if (this.img.isLoaded) { 
      ctxPara.clearRect(0, 0, canvasPara.width, canvasPara.height); 
      ctxPara.drawImage(this.img, this.xPos, this.yPos); // ERROR: 'Unknown Error'. 
      this.yPos++; 
      console.log('animating'); 
     } 
    }; 
}; 

我又被卡住了。但是現在我甚至不知道原因......請幫忙!?

回答

0

演示:http://jsfiddle.net/m1erickson/ym55y/

幾個問題:

(1)爲了讓你可以使用窗口寬度:

window.innerWidth 

(2)setInterval的調用newParachute.animate。

setInterval(newParachute.animate, newParachute.speed); 

this內動畫窗口對象 - 而不是降落傘對象。

給出正確this動畫可以使用call方法是這樣的:

var newParachute = new parachute(); 

setInterval(function(){newParachute.animate.call(newParachute);}, newParachute.speed); 

(3)您需要處理清算之前繪製的圖像或他們仍然會顯示您的畫布上。

+0

非常感謝! (3):我用下面這行代碼處理: ctxPara.globalCompositeOperation ='copy'; – Reijo