在 canvas 中沿相反方向移动矩形

Moving rectangles in opposite directions in canvas

原谅问题的幼稚,对 JS 完全陌生。

我已经成功地得到一个在 canvas 中来回移动的矩形,我想添加第二个相反的方向(甚至上下)

唯一的问题是第二个矩形是静态的,我无法让它移动。

我可以在第一个方块的相同函数中放置一个新的 ctx.fillRect(x,y,w,h) 吗?

作为 atm,它看起来像这样:

function drawSquare(ctx) {

    clearCanvas(ctx); 
    ctx.fillStyle = "black";
    ctx.fillRect(xpos, 140, 20, 20);
    if(direction==="goright"){
        if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
    } if(direction==="left"){
        if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}   
    }
    // This is the second square i am having trouble with??
    ctx.strokeStyle = "black";
    ctx.strokeRect(780, 200, 20, 20)

    if(direction==="goright"){
        if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
    } if(direction==="left"){
        if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}   
    }

如果需要,我有我的变量和其他编码。 但是我需要为第二个方块设置第二个方向变量吗? 或者我需要为它设置一个完全不同的函数和新的 setInterval 吗?

您需要在更新 xpos 变量后 绘制第二个矩形,并使用 xpos 变量。

function drawSquare(ctx) {
    clearCanvas(ctx); 
    if(direction==="goright"){
        if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
    } if(direction==="left"){
        if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}   
    }
    ctx.fillStyle = "black";
    ctx.fillRect(xpos, 140, 20, 20);

    if(direction==="goright"){
        if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
    } if(direction==="left"){
        if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}   
    }
    // This is the second square i am having trouble with??
    ctx.strokeStyle = "black";
    ctx.strokeRect(xpos, 200, 20, 20)
}

这是一个工作片段

var
    ctx = document.getElementById('c').getContext('2d'),
    xpos = 0, t,
    canvasWidth = 256,
    direction = "goright"
; 

function drawSquare(ctx) {
        ctx.clearRect(0,0,256,256); 
        if(direction==="goright"){
            if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
        } if(direction==="left"){
            if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}   
        }
        ctx.fillStyle = "black";
        ctx.fillRect(xpos, 140, 20, 20);
        
        if(direction==="goright"){
            if(xpos<canvasWidth - 20){xpos = xpos + 5;}else{direction = "left";}
        } if(direction==="left"){
            if(xpos>0){xpos = xpos - 5;}else{direction = "goright";}   
        }
        // This is the second square i am having trouble with??
        ctx.strokeStyle = "black";
        t = window.performance.now();
        ctx.strokeRect(xpos + Math.cos(t * 0.001) * 32, Math.sin(t * 0.001) * 118 + 128, 20, 20)
    }

window.requestAnimationFrame(function draw() {
drawSquare(ctx);
  window.requestAnimationFrame(draw);
});
<canvas width="256" height="256" id="c"></canvas>