Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript初始化图像数组_Javascript_Arrays_Closures - Fatal编程技术网

Javascript初始化图像数组

Javascript初始化图像数组,javascript,arrays,closures,Javascript,Arrays,Closures,我试图初始化一个Image()对象数组,每个对象都有一个不同的x位置。但是,数组中的所有对象似乎都以相同的x位置结束。我尝试过寻找解决方案,似乎它与“关闭”有关,但我不确定如何修复它 这是我的代码: function initPieces(){ for (var i = 0; i<8; i++) { var piece = new Image(); piece.x = 5 + i*50; piece.y = 5; piece.src = "image

我试图初始化一个
Image()
对象数组,每个对象都有一个不同的
x
位置。但是,数组中的所有对象似乎都以相同的
x
位置结束。我尝试过寻找解决方案,似乎它与“关闭”有关,但我不确定如何修复它

这是我的代码:

function initPieces(){
  for (var i = 0; i<8; i++) {
    var piece = new Image();

    piece.x = 5 + i*50;
    piece.y = 5;

    piece.src = "images/piece.png";

    piecesArray.push(piece);

    alert(i + ", " + piecesArray[i].x);
  }
}
函数initPieces(){

对于(var i=0;i我找不到
HTMLImageElement.x
HTMLImageElement.y
属性的明确参考(因为使用
new Image()
),但说它们是只读的和实验性的,不能在生产代码中使用

它们确实是只读的:在我做的一个快速测试中,它们可以被设置,但是之后读取值只会产生0


如果您想在将元素插入DOM后在页面中移动元素,请使用标准技术,例如操纵
piece.style.top

我找不到
HTMLImageElement.x
HTMLImageElement.y
属性的确切参考(因为使用
新图像()
),但表示它们是只读和实验性的,不用于生产代码

它们确实是只读的:在我做的一个快速测试中,它们可以被设置,但是之后读取值只会产生0


如果要在将元素插入DOM后在页面中移动元素,请使用标准技术,例如操纵
piece.style.top
您尚未将这些图像添加到DOM中,因此
x
y
offsetLeft
offsetTop
属性没有上下文(默认为zer0)

在操作图像之前,请先将图像添加到DOM,或者使用其他属性:

var piecesArray = [];
function initPieces(){
  for (var i = 0; i<8; i++) {
    var piece = new Image();

    piece.tempX = (i*50 + 5); // temporary place holder for X
    piece.y= 5; // this will not work; allows set, but does not change value

    piece.src = "images/piece.png";

    piecesArray.push(piece);

      alert(i + ": " + piecesArray[i].tempX);
  }
}
initPieces();
var-piecesArray=[];
函数initPieces(){

对于(var i=0;i您尚未将这些图像添加到DOM中,因此
x
y
offsetLeft
offsetTop
属性没有上下文(默认为zer0)

在操作图像之前,请先将图像添加到DOM,或者使用其他属性:

var piecesArray = [];
function initPieces(){
  for (var i = 0; i<8; i++) {
    var piece = new Image();

    piece.tempX = (i*50 + 5); // temporary place holder for X
    piece.y= 5; // this will not work; allows set, but does not change value

    piece.src = "images/piece.png";

    piecesArray.push(piece);

      alert(i + ": " + piecesArray[i].tempX);
  }
}
initPieces();
var-piecesArray=[];
函数initPieces(){

对于(var i=0;i使用
tempX
是我案例的解决方案,因为我在HTML5画布中使用它,所以我不确定
style.top
是否有用,因为图像不在DOM中。谢谢!使用
tempX
是我案例的解决方案,因为我在HTML5画布中使用它,所以我不确定
style.top
是否有用它很有用,因为图像不在DOM中。谢谢你!感谢你的解释,它完美地解释了为什么我的代码不工作。但是我没有提到它是在HTML5环境中使用的,这是我的错,所以我接受了另一个答案。谢谢你的解释,它完美地解释了为什么我的代码不工作。但是这是我的错因为没有提到它是在HTML5环境中使用的,所以我接受了另一个答案。