清除屏幕并在html5画布中移动元素

时间:2018-04-23 18:44:18

标签: javascript html5-canvas game-loop

我正在研究HTML5 canvas和JS的赛车游戏。因此,当汽车移动时,我想清除前一个屏幕并移动汽车。但它没有按预期工作。

代码:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var y = 110;
var x = 10;
var speed = 0.5;

function movePlayer(){
  //context.clearRect(0, 0, canvas.width, canvas.height);
  context.beginPath();
  var player = new Image();
  player.src = "http://www.clker.com/cliparts/J/W/v/e/2/z/vertical-top-view-of-car-md.png";
  player.onload = function(){
    context.drawImage(player, x, y, player.width*0.4, player.height*0.13);
  }

  y = y - speed;

  if (y < -15){
    y = 110;
  } 

  requestAnimationFrame(movePlayer);
}

requestAnimationFrame(movePlayer)

链接:https://jsfiddle.net/jackysatpal/6j4c5dod/1/

2 个答案:

答案 0 :(得分:1)

感谢Patrick Evans,我发现了问题所在。 通过创建新图像和设置源来制造错误。更改了代码,它现在正在运行。

代码:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var y = 110;
var x = 10;
var speed = 1.5;

var player = new Image();
player.src = "./images/p1.png";

function movePlayer(){
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(player, x, y, player.width*0.4, player.height*0.13);

  y = y - speed;

  if (y < -15){
    y = 110;
  } 

  requestAnimationFrame(movePlayer);

}

requestAnimationFrame(movePlayer)

链接:https://jsfiddle.net/jackysatpal/6j4c5dod/4/

答案 1 :(得分:0)

您可以通过在加载图像时启动绘图周期来进一步优化代码:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var y = 110;
var x = 10;
var speed = 0.5;

var player = new Image();
player.src = "http://www.clker.com/cliparts/J/W/v/e/2/z/vertical-top-view-of-car-md.png";
player.onload = function(){
  requestAnimationFrame(movePlayer)
}

function movePlayer(){
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.beginPath();

  context.drawImage(player, x, y, player.width*0.4, player.height*0.13);

  y = y - speed;

  if (y < -15){
    y = 110;
  } 

  requestAnimationFrame(movePlayer);
}