javascript - 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;
}
});
}
解决方案
我已经更新了小提琴。查看。您没有使用动态 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);
}
推荐阅读
- grafana - 如何使用 grafana 显示所有动态指标?
- php - 这似乎是一种允许用户公开共享数据的安全方式吗?
- c++ - Linux 上的 .NET Core - 元帅结构
- sql - 如何在sql中获取最近3天的数据
- sql-server - FreeTDS 和 unixodbc 安装和配置
- angular - 如何在 TypeScript 中使用附加属性扩展 fabric.Object
- javascript - 类型上不存在属性“defaultProps”
- python - 替换 Pandas 数据框中的值
- asp.net - 点网中数据的长期加密
- python - Mask-RCNN 项目