【发布时间】:2020-02-04 01:01:26
【问题描述】:
我正在 html5 画布中创建一个 2D 平台游戏。我正在尝试为精灵设置动画,使其切换到正在运行的图像和文具图像,以创建精灵正在运行的错觉。我尝试根据帧号更改精灵图像,但它只显示精灵运行不到一秒钟。这不是我的完整代码。只是与运行动画相关的部分。
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Game</title>
<style media="screen">
#canvas {
background-color: #87cefa;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
</body>
<script type="text/javascript" src="index.js">
</script>
</html>
index.js:
var canvas, ctx, player, playerPng, key, frameNo;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
player = {
w: 100,
h: 200,
x: 40,
y: canvas.height - 20
}
playerPng = new Image();
frameNo = 0;
key = false;
function loop() {
frameNo += 1;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(playerPng, player.x, player.y, player.w, player.h);
if(key === 39) {
if(frameNo % 100 === 0){
playerPng.src = "Running.png";
} else {
playerPng.src = "normal.png";
}
}
if(key === false){
playerPng.src = "normal.png";
}
window.requestAnimationFrame(loop);
}
window.addEventListener('keydown', function(e){
key = e.keyCode;
});
window.addEventListener('keyup', function(e){
key = false;
});
loop();
【问题讨论】:
标签: javascript html animation html5-canvas runtime