不能显示画布对象

Can't display canvas object

本文关键字:对象 布对象 显示 不能      更新时间:2023-09-26

伙计们,这是一个函数,应该在框架上显示一个红色的球,但它不是这样做的,我正在看一个教程,我做的一切都和他做的一样,但我不知道这里的问题是什么。求你了,我需要知道。如果有人能理解,请帮助…

var canvas,ctx,w,h,game=true;
var ball;
var BALL = function(x,y){
    this.x = x;
    this.y = y;
    this.color = "red";
    this.radius = 10;
    this.vx = 3;
    this.vy = -4;
}

window.onload = init;
function init() {
  canvas = document.getElementById("canvas");
  w = canvas.width;
  h = canvas.height;
  ctx = canvas.getContext('2d');
  ball = new BALL(w/2,h/2+50);
  beginGame();
}
function beginGame(){
  if(game){  
    ctx.clearRect(0,0,w,h);
      ball.x+=ball.vx;
      ball.y+=ball.vy;
      if((ball.x+ball.radius)+ball.vx>w || (ball.x-ball.radius)+ball.vx<0){
          ball.vx = -ball.vx;
      }
      ctx.fillStyle = ball.color;
      ctx.beginPath();
      ctx.arc(ball.x,ball.y,ball.radus,0,2*Math.PI,true);
      ctx.closePath();
      ctx.fill();
      window.requestAnimationFrame(beginGame);
  }else{
    //Game Over
  }
}// End of beginGame function 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>არკანოიდი</title>
<script src='tools.js'></script>
<script src='jquery-1.11.2.min.js' language='javascript' > </script>
<style>
canvas {
    border: 1px solid silver;
}
</style>
</head>
<canvas id="canvas" width="800" height="600"></canvas>
<body>
</body>
</html>

我不知道它是否会修复一切,但是你的画布在你的body标签之外。

1. 不要使用language='javascript'。这是不必要的。2. 如果你想显式地声明它为javascript,那么使用type="text/javascript"。这是自动的情况,所以你甚至不需要这样做。3.将画布放入body标签中。4. 使用窗口。addEventListener("load", init)代替window.onload(init)5.startgame函数内部:

function beginGame()
{
    // previous lines omitted...
    ball = new BALL(x, y);
    // other lines here...
}