0

我试图在屏幕上显示三张扑克牌,出于某种原因,每次我运行代码时都会出现类型错误,我已经尝试了一切尝试修复它,但没有任何效果。我认为问题出在数组/对象构造函数中,但我认为一切都在其中。

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

}
4

2 回答 2

1

您似乎将Card函数对象的静态属性与 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();
};
于 2012-08-29T19:52:40.633 回答
1

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

这不应该是

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

于 2012-08-29T19:21:26.487 回答