如何将clearRect应用于画布中的仅一个对象

时间:2019-03-05 05:39:03

标签: javascript canvas

 <input type='button' value='play' onclick='animation()'>

我正在创建我的第一个JavaScript画布游戏,到目前为止,我有一个可以移动的矩形和一个在屏幕上动画的球。我遇到一个问题,当我调用我的动画函数时,它将摆脱矩形,因为它清除了除球的整个画布,反之亦然。我需要一种无需清除整个画布即可清除其先前位置的方法。

谢谢。

这是我的代码。

let canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
let xPos = 10
let yPos = 10
document.addEventListener('keydown', movement)

window.onload = init()
function init(){
    ctx.beginPath();
    ctx.fillStyle = 'red'
    ctx.fillRect(10,10,30,30);
}
init()

function movement(e){
//Player Controls 
// horizontal and vertical movement
    if (e.keyCode === 87 ){
        ctx.clearRect(0,0, canvas.width, canvas.height);
        yPos = yPos - 5;
        ctx.fillRect(xPos,yPos,30,30)
    }
     if(e.keyCode === 83){
         ctx.clearRect(0,0, canvas.width, canvas.height);
         yPos = yPos + 5;
         ctx.fillRect(xPos,yPos,30,30)
    }
    if(e.keyCode === 65){
        ctx.clearRect(0,0, canvas.width, canvas.height);
        xPos = xPos - 5;
        ctx.fillRect(xPos,yPos,30,30)
    }
    if(e.keyCode === 68){
        ctx.clearRect(0,0, canvas.width, canvas.height);
        xPos = xPos + 5;
        ctx.fillRect(xPos,yPos,30,30)
    }
  
 
    // keeping the player inside the canvas
    xPos = Math.min(Math.max(xPos, 0+5), canvas.width-35);
    yPos = Math.min(Math.max(yPos, 0+5), canvas.height-35); 
}
let dx = 1
let x = 0
function animation(){
    requestAnimationFrame(animation);
    ctx.clearRect(0,0,canvas.width,canvas.height);
    
    ctx.beginPath();
    ctx.arc(x,250,40,0,Math.PI*2);
    ctx.strokeStyle = 'blue';
    ctx.stroke();
    x=x+dx;
}

0 个答案:

没有答案