2012-08-29 112 views
0

我想在屏幕上顯示三張撲克牌,由於某種原因,每當我運行代碼時出現類型錯誤,我嘗試了一切嘗試修復它,但沒有任何工作。我認爲問題出在數組/對象構造函數中,但我認爲所有內容都在這些內部。Javascript陣列和對象/類

"use strict"; 

function main(){ 
var cvs = document.getElementById("foo"); 
var ctx = foo.getContext("2d"); 
function Card(posX, posY, imgX, imgY){ 
    this.posX = posX; 
    this.posY = posY; 
    this.imgX = imgX; 
    this.imgY = imgY; 
    this.width = 97; 
    this.height = 129; 
} 
Card.img = new Image(); 
Card.img.src = "allcards.png"; 
var cards = [new Card(0,0,0,0), new Card(400,400,194,258), new Card(200,200,291,387)]; 
var greaterX = false; 
var lessX = false; 
var greaterY = false; 
var lessY = false; 
var offsetX; 
var offsetY; 
setInterval(draw, 10); 

function draw(){ 
    ctx.fillStyle="rgb(0,255,255)"; 
    ctx.clearRect(0,0,600,600); 
    ctx.drawImage(Card.img,cards[1].imgX,cards[1].imgY,Card.width,Card.height,cards[1].posX, cards[1].posY); 
    ctx.drawImage(Card.img,cards[2].imgX,cards[2].imgY,Card.width,Card.height,cards[2].posX, cards[2].posY); 
} 

} 
+0

什麼是錯誤? –

+2

什麼是錯誤?一個問題是你使用的Card.width和Card.height看起來不像他們已經定義的。 –

+0

有一個typeerror總是出現在繪圖函數的第3行 – CRS

回答

1

var ctx = foo.getContext(「2d」);

如果不是這種

變種CTX = cvs.getContext( 「2D」);

1

你似乎混淆了這些卡實例的Card函數對象的靜態屬性 - 在widthheight屬性是實例屬性。

var cvs = document.getElementById("foo"); 
var ctx = cvs.getContext("2d"); 

function Card(posX, posY, imgX, imgY){ 
    this.posX = posX; 
    this.posY = posY; 
    this.imgX = imgX; 
    this.imgY = imgY; 
} 
// default values/methods, accessible and overwritable on all instances: 
Card.prototype.width = 97; 
Card.prototype.height = 129; 
Card.prototype.draw = function() { 
    ctx.drawImage(Card.img, this.imgX, this.imgY, this.width, this.height, this.posX, this.posY); 
}; 

// static property: 
Card.img = new Image(); 
Card.img.src = "allcards.png"; 
Card.img.onload = draw; 

var cards = [new Card(0,0,0,0), new Card(400,400,194,258), new Card(200,200,291,387)]; 

function draw(){ 
    ctx.fillStyle="rgb(0,255,255)"; 
    ctx.clearRect(0,0,600,600); 
    for (var i=0; i<2; i++) 
     cards[i].draw(); 
};