首页 > 解决方案 > html5画布移动元素

问题描述

我正在开发 HTML5 和 JS 的赛车游戏。我正在尝试使用箭头键移动汽车。但它不起作用。

您将如何在画布中移动元素,是否需要在移动元素之前清除整个画布窗口?

代码:

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

var yCoordinate = 115;
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var distance = 10;
var speed = 0.5;
var angle = 25;

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

startGame();

function startGame(){
  requestAnimationFrame(moveLane);
}

function moveLane(){
  clearCanvas();  
  drawCar();
  drawLane(10 - yCoordinate);
  drawLane(60 - yCoordinate);
  drawLane(110 - yCoordinate);
  //speed of the lane
  yCoordinate = yCoordinate - 0.4;
  //if lane crossed the bottom boundrary then reset the y co-ordinate
  if (yCoordinate <= -145){
    yCoordinate = 115;
  }

  requestAnimationFrame(moveLane);
}

function drawCar(){
  context.drawImage(car, canvasWidth/2, canvasHeight/4, car.width*0.4, car.height*0.13);
  setCarControls();
}

function moveCarLeft(){
  clearCanvas();
  var x = canvasWidth/2 - distance;
  context.drawImage(car, x, canvasHeight/4, car.width*0.4, car.height*0.13);
}

function drawLane(yCoordinate){
  context.fillStyle = "#ffffff";
  context.fillRect(canvasWidth/2, yCoordinate, 10, 20);
}

function clearCanvas(){
  context.clearRect(0, 0, canvasWidth, canvasHeight);
}

function setCarControls() {
  document.addEventListener('keydown', function(e){
    switch(e.keyCode){
      case 37: 
        console.log('left');
        requestAnimationFrame(moveCarLeft);
        break;
      case 38:
        console.log('up');
        break;
      case 39:
        console.log('right');
        break;
      case 40:
        console.log('down');
        break;
    }
  });
}

直播链接:https ://jsfiddle.net/jackysatpal/6j4c5dod/6/

标签: javascripthtml5-canvas

解决方案


我已经更新了小提琴。查看。您没有使用动态 x 坐标。

https://jsfiddle.net/6j4c5dod/7/

function moveCarLeft(){
 clearCanvas();
 currentX = currentX - 0.1;
 context.drawImage(car, currentX, canvasHeight/4, car.width*0.4, car.height*0.13);
 }

推荐阅读