如何镜像和反转画布对象的移动?



所以我有两个对象。正方形A和平方B。正方形 A 跟随光标的移动。现在我想让 SquareB 镜像 SquareA 的运动,但相反。

例:

正方形A向左走,正方形B向右走。 SquareA下跌,SquareB上涨。

我目前有这段代码可以让方块 B 跟随方块 A

// update squareA to mouse
squareA.x = mouseX - (squareB.width * .5);
squareA.y = mouseY - (squareB.height * .5);
// update squareB to squareA
squareB.x = squareA.x;
squareB.y = squareA.y  - (squareA.height * 2);

但是我想不出扭转squareB运动的方法。

这是问题的笔

https://codepen.io/ricjonsu098/pen/xxZrvZP?editors=0010

完整解决方案:

// create a canvas to work with
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
// style canvas
canvas.id     = "canvas";
canvas.width  = 400;
canvas.height = 400;
canvas.setAttribute("style", "border: 1px solid black;");
// get 2D context
var context = canvas.getContext('2d');
var squareA = {x:10, y:30, width: 25, height: 25 };
var squareB = {x:10, y:30, width: 25, height: 25 };
// place holders for mouse x,y position
var mouseX = 0;
var mouseY = 0;
var centerX = canvas.width/2;
var centerY = canvas.height/2;

// Render Loop
function update() {
// update squareA to mouse
squareA.x = mouseX - (squareB.width * .5);
squareA.y = mouseY - (squareB.height * .5);
// update squareB to squareA
squareB.x = centerX - (squareA.x - centerX);
squareB.y = centerY - (squareA.y  - centerY);

// clear the canvas
canvas.width = canvas.width;

// draw first rectangle
context.fillStyle = "blue";
context.fillRect (squareA.x,squareA.y,squareA.width,squareA.height);

// draw second rectangle
context.fillStyle = "green";
context.fillRect (squareB.x,squareB.y,squareB.width,squareB.height);

}
// update mouse position
canvas.onmousemove = function(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
update();
}

请注意,我摆脱了间隔。您可以只更新鼠标移动。

我希望这有帮助,400 是画布大小

// update squareA to mouse
squareA.x = mouseX;
squareA.y = mouseY;
// update squareB to squareA
squareB.x = 400 - squareA.x;
squareB.y = 400 - squareA.y;