无法使用javascript

时间:2017-09-29 18:00:03

标签: javascript html html5 html5-canvas

我似乎无法将我的图像渲染到画布上。出于某种原因,它只是没有出现。我在网上寻找解决方案,但没有一个能运作。

这是我的代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Battlefield Online</title>
    <canvas id="canvas" width="1800" height="800"></canvas>
    <script src="/socket.io/socket.io.js"></script>
  </head>
  <body>
    <script type="text/javascript">


//Socket io connection
    var socket = io();
//Grabing canvas
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var img = document.getElementById("scream");
document.onkeydown = function(event) {
  if(event.keyCode === 39) {// right arrow
    socket.emit('keyPress', {inputId: 'right', state: true});
  }
  else if(event.keyCode === 37) {// left arrow
    socket.emit('keyPress', {inputId: 'left', state: true});
  }
  else if(event.keyCode === 38) {// up arrow
    socket.emit('keyPress', {inputId: 'up', state: true});
  }
  else if(event.keyCode === 32) {// space
    socket.emit('keyPress', {inputId: 'space', state: true});
  }
}

document.onkeyup = function(event) {
  if(event.keyCode === 39) {// right arrow
    socket.emit('keyPress', {inputId: 'right', state: false});
  }
  else if(event.keyCode === 37) {// left arrow
    socket.emit('keyPress', {inputId: 'left', state: false});
  }
  else if(event.keyCode === 38) {// up arrow
    socket.emit('keyPress', {inputId: 'up', state: false});
  }
  else if(event.keyCode === 32) {// space
    socket.emit('keyPress', {inputId: 'space', state: false});
  }
}



socket.on('newPosistions', function(data){

  context.fillStyle = '#000';
  context.fillRect(0, 0, canvas.width, canvas.height);
  var img = new Image();
  img.onload = function(){        
    context.drawImage(img,0,0, 100, 100); 
  };  
  img.src = "2d-game-bg.jpg";

  for(var i = 0; i < data.length; i++) {
    context.fillStyle = 'rgba('+ data[i].color[0] +', '+ data[i].color[1] +', '+ data[i].color[2] +', 1)';
    context.fillRect(data[i].x, data[i].y, 50, 100);
  }
});



</script>

我绘制图像的部分位于socket.on('newPo ... 这应该有效,因为我已经按照教程和示例确切地说哪些有效,但似乎没有一个对我有效。

我已使用此代码加载图像:

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" width="220" height="277" src="2d-game-bg.jpg" alt="The Scream">

<p>Canvas:</p>
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img, 10, 10);
}
</script>

<p><strong>Note:</strong> The canvas tag is not supported in Internet 
Explorer 8 and earlier versions.</p>

</body>
</html>

此代码是w3schools教程的精确副本。它适用于我的图像,因此它确实存在,并且服务器没有渲染它的问题。

任何人都可以帮我解决这个问题吗?

0 个答案:

没有答案