试图改变 x-position-variable,但只有值改变,而不是 ctx 的位置

Trying to change the x-position-variable, but only the value changes, not the position of the ctx

我正在尝试实现点击和拖动功能,这样当我点击并按住时,我将能够移动 "brick"。但是当我尝试在我的 mousemove 事件监听器中将 x 位置更改为 e.clientX 时,只有变量的值发生变化,而砖块不会改变位置。即使我只是将 x 位置更改为数字,也只会更改值。我尝试了 console.log 和 var,正如我所说,值发生了变化。

var brick1 = { //my brick variables
 x: 0, 
 y: 0, 
 width: brickWidth, 
 height: brickHeight,
 img: "media/brick.png",
 clicked: false
 };
  
var myBrick1 = new object(brick1.img, brick1.x, brick1.y, brick1.width, brick1.height); //my actual brick object

document.addEventListener("mousemove", mouseMoveHandler, false);
function mouseMoveHandler(e){
  var mouseX = e.clientX - (canvas.offsetLeft+10);
  var mouseY = e.clientY - (canvas.offsetTop+10);

  if(brick1.clicked){
    brick1.x = 120; //The value changes, but not the position
    brick1.x = mouseX - (brick1.width/2);
    console.log(brick1.clicked);
    console.log(brick1.x);
  }
}
 
 

谁能告诉我为什么会这样?希望如何解决它? 如果您需要我的代码中的更多样本来查看问题,请告诉我。

您希望按值传递在您的构造函数中作为按引用传递。

var myBrick1 = new object(brick1.img, brick1.x, brick1.y, brick1.width, brick1.height); //my actual brick object

此处您使用 new objectbrick1 的值构造并分配给新对象。我假设你的构造函数看起来像

function object(img, x, y, w, h) {
  this.img = img;  /* object so reference assignment */
  this.x = x;      /* number so value assignment */
  this.y = y;      /* number so value assignment */
  this.w = w;      /* number so value assignment */
  this.h = h;      /* number so value assignment */
  /* some methods ect... */
}

当您随后更改 brick1 的值时

if(brick1.clicked){
  brick1.x = 120; //The value changes, but not the position
  brick1.x = mouseX - (brick1.width/2);
  console.log(brick1.clicked);
  console.log(brick1.x);
}

这只会更改属性 xy 的 brick1 值。因为它们是作为值而不是引用传递给对象的。

您可以将代码更改为

myBrick1.x = 120;

幸好这不是通过引用分配的,否则您的所有积木都将具有相同的 x、y 坐标。完整修改后的声明:

if(brick1.clicked) {
  myBrick1.x = 120; //The value changes, but not the position
  myBrick1.x = mouseX - (myBrick1.width/2);
  console.log(brick1.clicked);
  console.log(brick1.x);
}