0

它非常困惑我正在设计一个 2d 游戏,我使用此代码将图像绘制到画布上,警报方法返回 background.x = 0 !但是当我将 x 更改为 z 或任何字母时,它会返回数字 400 i !为什么 background.x 总是等于零???

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

function loadResources(){
background = new Image();
background.src = "11.jpg";
background.width = 128;
background.height = 128;
background.x = 400;
background.y = 450;

}

function drawimage(){
alert(background.x);
context.drawImage(background,background.x,background.y,background.width,background.height);

}

function gameLoop() {
drawimage();
}


loadResources();
setInterval(gameLoop, 1000/60); 
4

1 回答 1

1

与其他对象不同,您实际上无法设置不属于它的 Image 对象的属性。如您所见,当您在设置它们后尝试访问它们时,这些属性将不可用。您可以按如下方式稍微修改您的代码以获得您正在寻找的行为:

var canvas = document.getElementById('game'); 
var context = canvas.getContext('2d');
var resources = {};

function loadResources(){
    resources.background = new Image();
    resources.background.src = "11.jpg";
    resources.background.width = 128;
    resources.background.height = 128;
    resources.backgroundx = 400;
    resources.backgroundy = 450;
}

function drawimage(){
    console.log(resources.backgroundx);
    context.drawImage(resources.background,resources.backgroundx,resources.backgroundy,resources.background.width,resources.background.height);
}

function gameLoop() {
    drawimage();
}


loadResources();
setInterval(gameLoop, 1000/60); 
于 2013-07-28T05:50:29.790 回答