[英]How To Use Clear Rect Function For Movement In JavaScript
我正在使用純JavaScript制作游戲,但clearRect函數無法正常工作,下面是代碼:
//player's location
var playerX = 250;
var playerY = 325;
document.addEventListener('keydown', function(e) {
if (e.key === 'w' && playerY >= borderW && movement === true) {
playerY -= playerSpeed;
//Clears the head of the Protagonist
ctx.clearRect(playerX + 2.5, playerY + 2.5, 20, 20);
//Clears the body of the protagonist
ctx.clearRect(playerX + 5, playerY + 17.5, 15, 25);
drawProtagonistFacingUp();
}
if (e.key == 'd' && playerX < borderD && movement === true) {
playerX += playerSpeed;
ctx.clearRect(playerX, playerY, -200, 200);
drawProtagonistFacingRight();
}
if (e.key == 's' && playerY < borderS && movement === true) {
playerY += playerSpeed;
ctx.clearRect(playerX, playerY - 15, 200, 200);
drawProtagonistFacingDown();
}
if (e.key == 'a' && playerX > borderA && movement === true) {
playerX -= playerSpeed;
ctx.clearRect(playerX, playerY, 200, 200);
drawProtagonistFacingLeft();
}
});
應該發生的情況是,當玩家按下w,a,s或d進行移動時,它將清除屏幕上的舊玩家圖像並繪制新的圖像。 但是,它現在所做的只是清除少量的播放器圖像。 如果可能的話,一個簡單的解決方案將是有幫助的。 謝謝。
使用畫布設置動畫的方式設置了一個主要的動畫循環函數,該函數由requestAnimationFrame
調用
function update(time){ // requestAnimationFrame calls this function with the
// argument time. Time is in ms (1/1000th second) but
// accurate to 1/1,000,000th second, 0.001ms
... your code
requestAnimationFrame(update); // request the next frame
}
requestAnimationFrame(update); // start the animation
在標准設置下,瀏覽器每秒將調用該函數60次。
與其跟蹤並清除每個對象然后重新渲染,不如清除整個畫布要簡單得多。 這可以通過幾種方法完成
function update(time){
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); // Make all pixels
// transparent
// or
ctx.fillStyle = "black"; // can use solid colour, gradient, or pattern
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
// or
// use a background image
ctx.drawImage(backgroundImage,0,0,ctx.canvas.width,ctx.canvas.height);
... your code
requestAnimationFrame(update); // request the next frame
}
requestAnimationFrame(update); // start the animation
畫布清除后,您可以按順序渲染對象,最后一個對象將出現在之前繪制的對象上。 該方法大大簡化了您的動畫代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.