Javascript和画布问题

时间:2015-10-27 04:17:07

标签: javascript html5-canvas

我有一个问题,我的javascript没有做任何事情,当这里加载的页面是我的HTML和我的javascript我难倒我不知道问题是什么(对不起我在我的iPhone上做了这个差的间距)< / p>

的index.php

    <canvas id="breakout" width="480" height="320"></canvas>

   <script>

    var canvas =  document.getElementById("breakout") ;
    var ctx = canvas.getContext("2d");


    var x = canvas.width/2;
    var y = canvas.height-30;
    var mx = 2;
    var my = -2;

    function checkCollision{
    if(y + my < 0){
    my = -my;
    }
    if(y + my > canvas.height){
    my = -my;
    }
    if(x + mx > canvas.width-ballRadius){
    mx = -mx;
    }
    if(x + mx < ballRadius){
    mx = -mx;
    }
    }

    function drawBall{
     var ballRadius = 10;
     ctx.beginPath();
     ctx.arc(x,y,ballRadius,0, Math.PI*2);
     ctx.fillStyle = "#0095DD";
     ctx.fill();
     ctx.closePath();
    }

    function drawing{
     ctx.clearRect(0,0,canvas.width,canvas.height);
     drawBall();
     x += mx;
     y += my;
     checkCollision();
      }

     setInterval(drawing,10);

    </script>

1 个答案:

答案 0 :(得分:2)

您没有正确定义您的功能。您需要定义如下函数:

function foo() {
    ...
}

这样做的:

function foo{
    ...
}

无效,将导致控制台出错。此外,由于ballRadius在许多函数中使用,因此在函数drawBall

之外定义它
var x = canvas.width/2;
var y = canvas.height-30;
var mx = 2;
var my = -2;
var ballRadius = 10; // Added

var canvas =  document.getElementById("breakout") ;
var ctx = canvas.getContext("2d");


var x = canvas.width/2;
var y = canvas.height-30;
var mx = 2;
var my = -2;
var ballRadius = 10;

function checkCollision(){
    if(y + my < 0){
      my = -my;
    }
    if(y + my > canvas.height){
      my = -my;
    }
    if(x + mx > canvas.width-ballRadius){
      mx = -mx;
    }
    if(x + mx < ballRadius){
      mx = -mx;
    }
}

function drawBall(){
     ctx.beginPath();
     ctx.arc(x,y,ballRadius,0, Math.PI*2);
     ctx.fillStyle = "#0095DD";
     ctx.fill();
     ctx.closePath();
}

function drawing() {
     ctx.clearRect(0,0,canvas.width,canvas.height);
     drawBall();
     x += mx;
     y += my;
     checkCollision();
}

     setInterval(drawing,10);
<canvas id="breakout" width="480" height="320"></canvas>