[英]Can't get image to change on keypress on canvas
我要制作它,以便當我按向左按鈕時,它會顯示要向左移動的圖像集。 (我正在制作RPG游戲。)我不知道如何使用Spritesheet,因此我最終分別加載每個圖像以使事情變得容易。
這是我到目前為止的內容:
<script>
function initCanvas(){
var canvas = document.getElementById('my_canvas')
var ctx = canvas.getContext('2d');
//Variables
var cw = canvas.width;
var ch = canvas.height;
var x = 20;
var y = 20;
var width = 40;
var height = 40;
//----------------
//Char (Spritesheet soon)
//----------------
var charup = new Image();
charup.src = "up.png";
var chardown = new Image();
chardown.src = "down.png";
var charleft = new Image();
charleft.src = "left.png";
var charright = new Image();
charright.src = "right.png";
//
draw(); //Executes the Draw Function
//
//-------------
//WASD Controls
//-------------
document.addEventListener("keydown", move, false);
function move(event){
if(event.keyCode == 87){ //w
ctx.drawImage(charup, x, y, width, height);
if(y >= 20){
y-=20;
}
else if(y < 20){
y = 460;
}
}
if(event.keyCode == 65){ //a
ctx.drawImage(charleft, x, y, width, height);
if(x >= 20){
x-=20;
}
else if(x < 20){
x = 460;
}
}
if(event.keyCode == 83){ //s
ctx.drawImage(chardown, x, y, width, height);
if(y+height <= 490){
y+=20;
}
else if(y+height > 460){
y = 0;
}
}
if(event.keyCode == 68){ //d
ctx.drawImage(charright, x, y, width, height);
if(x+width <= 490){
x+=20;
}
else if(x+width > 490){
x = 0;
}
}
draw();
//Idea for sprite: If press right it goes right and loads a gif while going right...
//And when "keyup" or keyrelease or whatever, it stops the animation
//Or loads a neutral one facing the same direction.
}
//--------------
//Draw Function
//--------------
function draw(){
//Clears rect for animation purposes
ctx.clearRect(0, 0, cw, ch);
ctx.fillStyle = "green";
//ctx.fillRect(x, y, 20, 20);
ctx.drawImage(chardown, x, y, width, height);
}
}
//------------
//Game Loop
//------------
window.addEventListener('load', function(event){
initCanvas();
});
</script>
問題出在繪制函數上,該函數可在每次繪制時重新設置字符圖像。
解決方案是聲明一個新變量,該變量將承載角色的當前圖片:
var imgPlayer = new Image();
imgPlayer.src = "down.png"; //This is your default image.
下一步是更改鍵偵聽器功能,以便更改播放器圖像的來源(也請刪除此功能中所有角色的繪制)。 像這樣:
if(event.keyCode == 87){ //w
imgPlayer.src = charup.src;
//the rest of your code...
}
最后,在您的繪圖功能中:
ctx.drawImage(imgPlayer, x, y, width, height);
-----在這里結束答案,下面的東西只是為了娛樂-------
為了好玩,這是我前一段時間開始的未完成游戲。 http://home.niddro.com/HTML5/supergoose/SuperGoose.html角色的腳上有3張圖像,隨着玩家移動他的腳而循環。 我以超級馬里奧兄弟的概念為基礎。
有趣的事實2:在另一款游戲中,我循環了2張腳部模糊的圖像,從而使兔子運行得非常快:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.