绘制图像到画布问题

时间:2013-07-28 05:30:16

标签: javascript oop html5-canvas

我非常困惑我正在设计一个2D游戏,我使用此代码绘制图像到画布警报方法返回background.x = 0!但当我将x更改为z或任何字母时,它返回数字400我!为什么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); 

1 个答案:

答案 0 :(得分: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);