如何使用javascript中的箭头键在画布上移动图像

时间:2016-04-19 08:23:29

标签: javascript html image canvas keypress

我尝试了几种不同的方法,但我无法让我的形象移动。每当我尝试调整箭头按键的代码时,它似乎只会让我的画布缩小,而我的玩家模型(太空人)也会消失。

这是我继续回归的“绘图板”,以及到目前为止我所拥有的。

// Get the canvas and context
var canvas = document.getElementById("space"); 
var ctx = canvas.getContext("2d");
canvas.width = 1920;
canvas.height = 700;


// Create the image object
var spaceperson = new Image();

// Add onload event handler
spaceperson.onload = function () {
   // Done loading, now we can use the image
   ctx.drawImage(spaceperson, 280, 300);
};


// artwork by Harrison Marley (using make8bitart.com)
spaceperson.src = "http://i.imgur.com/Eh9Dpq2.png";`

我对javascript很新,我只想弄清楚如何使用箭头键移动specperson图像。我试图让空间人员上课来访问他们的x,y值,但我似乎无法在不使用.onload的情况下绘制图像

4 个答案:

答案 0 :(得分:1)

这是一段稍微修改过的游戏代码,我在前面徘徊了一段时间。如果您想查看更多代码,请查看complete JS on GitHub。游戏不完整但你应该收集一些有用的线索,了解如何在画布上移动图像。

[

issue: {

 comments: [

    {
     .
     .
    },
    {
     .
     .
    }
 ]

events : [

    {
     .
     .
    },
    {
     .
     .
    }
 ]

]

]

答案 1 :(得分:1)

我不确定,但我认为这可以提供帮助。



// Get the canvas and context
var canvas = document.getElementById("space"); 
var ctx = canvas.getContext("2d");
canvas.width = 1920;
canvas.height = 700;
var x = 280;
var y = 300;

// Create the image object
var spaceperson = new Image();

spaceperson.addEventListener("keypress", press);

// Add onload event handler
spaceperson.onload = function () {
   // Done loading, now we can use the image
   ctx.drawImage(spaceperson, x, y);
};

function press(event) {
  if(event.keyCode == 37) {//LEFT
    x = x - 1;
  } else if(event.keyCode == 38) {//UP
    y = y - 1;
  } else if(event.keyCode ==39) {//RIGHT
    x = x + 1;
  } else if(event.keyCode == 40) {//DOWN
    y = y + 1;
  }
  draw();
}

function draw(){
  ctx.drawImage(spaceperson,x,y);
}



// artwork by Harrison Marley (using make8bitart.com)
spaceperson.src = "http://i.imgur.com/Eh9Dpq2.png";




答案 2 :(得分:1)

这里有一个更完整的例子:

logger.js

修改

  
    

一个简单的问题(我希望);如果我以后添加其他对象,我会检查update()中的冲突吗?

  

这仍然是一个非常基本的例子。 //just a utility function image(url, callback){ var img = new Image(); if(typeof callback === "function"){ img.onload = function(){ //just to ensure that the callback is executed async setTimeout(function(){ callback(img, url) }, 0) } } img.src = url; return img; } //a utility to keep a value constrained between a min and a max function clamp(v, min, max){ return v > min? v < max? v: max: min; } //returns a function that can be called with a keyCode or one of the known aliases //and returns true||false wether the button is down var isKeyDown = (function(aliases){ for(var i=256, keyDown=Array(i); i--; )keyDown[i]=false; var handler = function(e){ keyDown[e.keyCode] = e.type === "keydown"; e.preventDefault(); //scrolling; if you have to suppress it }; addEventListener("keydown", handler, false); addEventListener("keyup", handler, false); return function(key){ return(true === keyDown[ key in aliases? aliases[ key ]: key ]) } })({ //some aliases, to be extended up: 38, down: 40, left: 37, right: 39 }); // Get the canvas and context var canvas = document.getElementById("space"); canvas.width = 1920; canvas.height = 700; var ctx = canvas.getContext("2d"); //the acutal image is just a little-part of what defines your figue var spaceperson = { image: image("//i.imgur.com/Eh9Dpq2.png", function(img){ spaceperson.width = img.naturalWidth; spaceperson.height = img.naturalHeight; //start the rendering by calling update update(); }), //position x: 60, y: 310, width: 0, height: 0, speed: 200 // 200px/s }; var lastCall = 0; //to calculate the (real) time between two update-calls //the render-fucntion function update(){ //taking account for (sometimes changing) framerates var now = Date.now(), time = lastCall|0 && (now-lastCall)/1000; lastCall = now; requestAnimationFrame(update); var sp = spaceperson, speed = sp.speed; //checking the pressed buttons and calculates the direction //two opposite buttons cancel out each other, like left and right var dx = (isKeyDown('right') - isKeyDown('left')) * time, dy = (isKeyDown('down') - isKeyDown('up')) * time; //fix the speed for diagonals if(dx && dy) speed *= 0.7071067811865475; // * 1 / Math.sqrt(2) if(dx) { //there is some movement on the x-axes sp.x = clamp( //calculate the new x-Position //currentPos + direction * speed sp.x + dx * sp.speed, //restraining the result to the bounds of the map 0, canvas.width - sp.width ); } //same for y if(dy) sp.y = clamp(sp.y + dy * sp.speed, 0, canvas.height - sp.height); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(sp.image, sp.x, sp.y); } - 函数的主要目的应该是作为主事件循环。 要按照必须发生的顺序触发必须在每个帧发生的所有事件。

update()

不是说你现在必须实现所有这些功能,而是要让你了解一个可能的结构。 不要害怕将(功能)的大任务分解为子任务 为每个敌人提供var lastCall = 0; function update(){ //I always want a next frame requestAnimationFrame(update); //handle timing var now = Date.now(), //time since the last call in seconds //cause usually it's easier for us to think in //tems like 50px/s than 0.05px/ms or 0.8333px/frame time = lastCall|0 && (now-lastCall) / 1000; lastCall = now; movePlayer(time); moveEnemies(time); moveBullets(time); collisionDetection(); render(); } function render(){ ctx.clear(0, 0, canvas.width, canvas.height); drawBackground(ctx); for(var i=0; i<enemies.length; ++i) enemies[i].render(ctx); player.render(ctx); } 功能可能是有意义的,这样你就可以为每个敌人实施不同的运动模式, 或者你说这个模式对于每个敌人都是(并且将会)完全相同,最好参数化,然后你可以在循环中处理它。
渲染也是一样,正如我在代码的最后部分所示。

答案 3 :(得分:0)

我找到了解决方案!

// Get the canvas and context
var canvas = document.getElementById("space"); 
var ctx = canvas.getContext("2d");
canvas.width = 1920;
canvas.height = 700;
var xPos = 60;
var yPos = 310;

// Create the image object
var spaceperson = new Image();

// Add onload event handler
spaceperson.onload = function () {
// Done loading, now we can use the image
ctx.drawImage(spaceperson, xPos, yPos);
};

function move(e){

if(e.keyCode==39){
    xPos+=10;
}
if(e.keyCode==37){
    xPos-=10;
}
if(e.keyCode==38){
    yPos-=10;
}
if(e.keyCode==40){
    yPos+=10;
}

canvas.width=canvas.width;
ctx.drawImage(spaceperson, xPos, yPos);

}

document.onkeydown = move;

// artwork by Harrison Marley
spaceperson.src = "http://i.imgur.com/Eh9Dpq2.png";