在画布中以相反方向移动矩形

时间:2015-03-27 02:41:51

标签: javascript canvas

原谅问题的无知,对JS来说是全新的。

我已经成功地在画布上来回了一个矩形,我希望在相反的方向上添加第二个(或者甚至是向上和向下)

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

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

at 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吗?

1 个答案:

答案 0 :(得分:2)

您需要在更新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)
}

这是一个工作片段

&#13;
&#13;
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);
});
&#13;
<canvas width="256" height="256" id="c"></canvas>
&#13;
&#13;
&#13;