Image不会在onLoad();中包含代码的JS画布上呈现;

问题描述 投票:0回答:1

我正在尝试使用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>



javascript html canvas
1个回答
0
投票

[drawImage是代码段中缺少的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>标签的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.