无法将图像添加到画布

时间:2016-07-30 16:56:05

标签: javascript html html5 canvas

我正在尝试在我的画布游戏中创建一个可移动的角色,但由于某种原因它不起作用,我不明白为什么。

// This will request which browser!
(function() {
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    window.requestAnimationFrame = requestAnimationFrame;
})();

// Setup of the game

// Create the canvas from the given element in the HTML
var canvas = document.getElementById("main"),
// Give the canvas 2D context
    context = canvas.getContext("2d"),

// Set the canvas with boundaries
// to allow the user not to go outside
// the boundaries
    height = 360,
    width = 600,



// Create the player giving some config
    player = {
  // this is where the player will start
      x : 50,
      y : height - 30,
      height : 30,
      width : 30
    },
    keys = [];

canvas.height = height;
canvas.width = width; 

var imgRepo = new function() {

  this.player = new Image();
  this.background = new Image();

  this.player.src = "../img/kangaroo.jpg";
  this.background.src = "../img/background.png";
}

function processUserInput() {

  // W
  if (keys[87]) {
    player.y = player.y - 10;
  }
  // S
  if (keys[83]){
    player.y = player.y + 10;
  }
  // A
  if (keys[65]) {
    player.x = player.x - 10;
  }
  // D
  if (keys[68]) {
    player.x = player.x + 10;
  }


  context.clearRect(0,0,width,height);
  context.fillStyle = "red";
  context.fillRect(player.x, player.y, player.width, player.height);

  requestAnimationFrame(processUserInput);
  requestAnimationFrame(drawImg);

}



document.body.addEventListener("keydown", function(e) {
    keys[e.keyCode] = true;
});

document.body.addEventListener("keyup", function(e) {
    keys[e.keyCode] = false;
});

window.addEventListener("load",function(){
    processUserInput();
});

我能够控制用“fillRect”绘制的块,所以我很困惑为什么我不能只添加图像而不是矩形。非常感谢任何帮助。

如果有人有兴趣,这是我的HTML。

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='utf-8'>
  <title> Jump Block </title>
  <link rel="stylesheet" property="stylesheet" type="text/css" href="css/style.css"/>
</head>

<body>
<header>
  <br>
  Press Tab to Begin, AWSD/ Arrow keys to move, and space to jump
  <br>
</header>

  <canvas id="main" width= "600" height="360" style="border: 1px solid green" tabindex="0" id="main">
    Your browser doesn't support HTML5.
  </canvas>

    <script src="js/game.js">
    </script>

</body>
</html>

0 个答案:

没有答案