使用onLoad()中的代码无法在JS画布上渲染图像;

时间:2019-12-13 04:49:37

标签: javascript html canvas

我正在尝试使用JS编写一个简单的游戏,其主要角色是一条鱼的图像。但是,无论尝试什么,都无法加载图像。我看了一些教程,但是都没有用。我已经读到我需要将图像代码放入onload();内,以便<img>在JS中被调用之前加载。我试过了,但是还是没用。我不断调整代码几个小时,发现控制台中出现drawImage();未定义的奇怪错误。我很困惑,但是我确定我确实缺少一些明显的东西,因为我对JavaScript还是很陌生。这是代码:

<!DOCTYPE html>
<html>
<head>
<title>Fish Game</title>
<style>

</style>
</head>
<canvas id="canvas" width="800" height="600" style="border:1px solid #000000; background: blue"></canvas>
<script>
var fishX = 400;
var fishY = 300;
var fishSpeed = 10;
var fishSize = 80;

 window.onload = function() {
        var framesPerSecond = 60;

        console.log("Page Loaded!");
        canvas = document.getElementById('canvas');
        canvasContext = canvas.getContext('2d');
        setInterval(function img() {
        }, 1000/framesPerSecond);
        drawImage(img, 10, 10);

 }

var img = document.getElementById("fish");

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '38' || '87') {
        // up arrow
        fishY = fishY + fishSpeed;
    }
    else if (e.keyCode == '40' || '83') {
        // down arrow
        fishY = fishY + fishSpeed;
    }
    else if (e.keyCode == '37' || '65') {
       // left arrow
       fishX = fishX + fishSpeed;
    }
    else if (e.keyCode == '39' || '68') {
       // right arrow
       fishX = fishX + fishSpeed;
    }
}
</script>

<body>
<img src="fish.png" id="fish" width="80px"  >


</body>
</html>



1 个答案:

答案 0 :(得分:0)

  

drawImage是摘要中缺少的canvasContext方法。

var fishX = 400;
var fishY = 300;
var fishSpeed = 10;
var fishSize = 80;

window.onload = function() {
  var framesPerSecond = 60;

  console.log("Page Loaded!");
  canvas = document.getElementById('canvas');
  canvasContext = canvas.getContext('2d');
  setInterval(function img() {}, 1000 / framesPerSecond);
  canvasContext.drawImage(img, 10, 10);

}

var img = document.getElementById("fish");

document.onkeydown = checkKey;

function checkKey(e) {

  e = e || window.event;

  if (e.keyCode == '38' || '87') {
    // up arrow
    fishY = fishY + fishSpeed;
  } else if (e.keyCode == '40' || '83') {
    // down arrow
    fishY = fishY + fishSpeed;
  } else if (e.keyCode == '37' || '65') {
    // left arrow
    fishX = fishX + fishSpeed;
  } else if (e.keyCode == '39' || '68') {
    // right arrow
    fishX = fishX + fishSpeed;
  }
}
<img src="https://cdn.sstatic.net/Img/unified/sprites.svg" id="fish" width="80px" />
<canvas id="canvas" width="800" height="600" style="border:1px solid #000000; background: blue"></canvas>

注意: <canvas>必须是<body>标签的一部分。