2

私は小さなオブジェクト指向スタイルの JavaScript デモを書いています - 画面上を動き回るボールの束を描くだけです。この時点では、空想も衝突検出も何もありません。私の Ball.js クラスが優れていると想定しても安全だと考えてください。

私の質問は次のとおりです: どこで ball.draw(context) を呼び出す必要がありますか? 私が設定した方法でボールを画面に描画する唯一の方法は、generateBalls() で呼び出しを行うことのようです。しかし、それは各ボールが 1 回だけ描画されることを意味します。

したがって、誰かがここで私のやり方の誤りを指摘できれば、本当に感謝しています。これは宿題ではなく、javascript と canvas をより適切に扱えるようにするためのものです。

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="ball.js"></script>
<script src="utils.js"></script>
...
    <canvas id="canvas" width="600" height="480"></canvas>
    <script type="text/javascript">
        window.addEventListener('load', eventWindowLoaded, false);

        function eventWindowLoaded() {
            canvasApp();    
        }

        function canvasSupport() {
            return true;    
        }

        function canvasApp() {
            if(!canvasSupport()) {
                return; 
            }
        }
        console.log("app entered");
        var numBalls = 45;
        //var numBalls = demo.numberofballs.value;
        var maxSize = 8;
        var minSize = 5; 
        var maxSpeed = maxSize + 5;
        var balls = new Array();
        var tempBall;
        var tempX;
        var tempY;
        var tempSpeed;
        var tempAngle;
        var tempRadius;
        var tempRadians;
        var tempXunits;
        var tempYunits;

        canvas = document.getElementById("canvas");
        context = canvas.getContext("2d");

        generateBalls();

        setInterval(drawScreen, 33);

        function generateBalls() {
            console.log("Make some balls");
            for(var index = 0; index < numBalls; index++) {
                var tempRadius = Math.floor(Math.random()*maxSize)+minSize;
                var ball = new Ball(tempRadius, "#000000"); 
                ball.x = tempRadius * 2 + (Math.floor(Math.random()*canvas.width) -  tempRadius * 2);
                ball.y = tempRadius * 2 + (Math.floor(Math.random()*canvas.height) - tempRadius * 2);
                ball.speed = maxSpeed - tempRadius;
                ball.angle = Math.floor(Math.random()*360);
                ball.dx = Math.cos(tempRadians) * tempSpeed;
                ball.dy = Math.sin(tempRadians) * tempSpeed;
                // here outputted balls but a stupid place to put it LOL
                balls.push(ball);



            }

        }

        function drawScreen() {
            console.log("draw screen");



            // loop through all balls and adjust their position
            // a BallManager could do this more cleanly
            for(var index = 0; index < balls.length; index++) {

                context.fillStyle="#EE00EE";
                context.fillRect(0,0,canvas.width, canvas.height);

                // Box
                context.strokeStyle = "#ff0043";
                context.strokeRect(1,1,canvas.width-2, canvas.height-2);

                // place balls
                context.fillStyle = "#ff8783";
                console.log("ball mover loop in drawscreen");
                // no var ball now

                ball = balls[index];
                ball.x += ball.dx;
                ball.y += ball.dy;
                ball.draw(context);
                //checkBoundaries(balls[index]);
                if(ball.x > canvas.width || ball.x < 0) {
                ball.angle = 180 - ball.angle;
                updateBall(ball);   
                    } else if(ball.y > canvas.height || ball.y < 0) {
                        ball.angle = 360 - ball.angle;
                        updateBall(ball);   
                        //ball.draw(context);
                }

            }

        }   

        //function checkBoundaries(ball) {
            //console.log("Check Bounds: " + " " + "ball.x: " + ball.x + " " + //"ball.y: " + ball.y);

        //}

        function updateBall(ball) {
            ball.radians = ball.angle * Math.PI / 180;
            ball.dx = Math.cos(ball.radians) * ball.speed;
            ball.dy = Math.sin(ball.radians) * ball.speed;
            //ball.draw(context);
        }

    </script>
</body>
</html>

アドバイスありがとう、マルク

4

2 に答える 2

2

例に複数のエラーが含まれています。変更したコードを確認してください。動作しますが、拡張して修正する必要があります。

<!DOCTYPE HTML>
<html>
  <head>
  <meta charset="utf-8">
  <title>Untitled Document</title>
  <script type="text/javascript">
    // next lines is a Ball() implementation code
    Ball = function(radius,color) {
        this.radius=radius;
        this.color=color;
    };
    Ball.prototype.x=0;
    Ball.prototype.y=0;
    Ball.prototype.speed=0;
    Ball.prototype.angle=0;
    Ball.prototype.dx=0;
    Ball.prototype.dy=0;
    Ball.prototype.radius=10;
    Ball.prototype.color="#000";
    Ball.prototype.draw=function() {

        context.beginPath();
        context.arc(this.x,this.y,this.radius,0,Math.PI*2,true);
        context.lineWidth = 5;
        context.strokeStyle = this.color; // line color
        context.stroke();
        context.closePath();
    };

    window.addEventListener('load', eventWindowLoaded, false);

    function eventWindowLoaded() {
        canvasApp();    

        //console.log("app entered");
        window.canvas = document.getElementById("canvas");
        window.context = canvas.getContext("2d");

        generateBalls();
        // if you want to use setInterval() instead replace next line
        setTimeout(drawScreen, 33);
    }

    function canvasSupport() {
        return true;    
    }

    function canvasApp() {
        if(!canvasSupport()) {
            return;
        }
    }

    var numBalls = 45;
    //var numBalls = demo.numberofballs.value;
    var maxSize = 8;
    var minSize = 5;
    var maxSpeed = maxSize + 5;
    var balls = new Array();
    var tempBall;
    var tempX;
    var tempY;
    var tempSpeed;
    var tempAngle;
    var tempRadius;
    var tempRadians;
    var tempXunits;
    var tempYunits;

    function generateBalls() {
        //console.log("Make some balls");
        for(var index = 0; index < numBalls; index++) {
            var tempRadius = Math.floor(Math.random()*maxSize)+minSize;
            var tempRadians = Math.random()*Math.PI;
            var tempSpeed = 10;
            var ball = new Ball(tempRadius, "#000000");
            ball.x = tempRadius * 2 + (Math.floor(Math.random()*canvas.width) -  tempRadius * 2);
            ball.y = tempRadius * 2 + (Math.floor(Math.random()*canvas.height) - tempRadius * 2);
            ball.speed = maxSpeed - tempRadius;
            ball.angle = Math.floor(Math.random()*360);
            ball.dx = Math.cos(tempRadians) * tempSpeed;
            ball.dy = Math.sin(tempRadians) * tempSpeed;
            // here outputted balls but a stupid place to put it LOL
            balls.push(ball);
        }
    }

    function drawScreen() {
        console.log("draw screen");


        context.fillStyle="#EE00EE";
        context.fillRect(0,0,canvas.width, canvas.height);

        // Box
        context.strokeStyle = "#ff0043";
        context.strokeRect(1,1,canvas.width-2, canvas.height-2);

        // loop through all balls and adjust their position
        // a BallManager could do this more cleanly
        for(var index = 0; index < balls.length; index++) {
            // place balls
            context.fillStyle = "#008700";
            //console.log("ball mover loop in drawscreen");
            // no var ball now

            ball = balls[index];
            ball.x += ball.dx;
            ball.y += ball.dy;
            ball.draw(context);
            //checkBoundaries(balls[index]);
            if(ball.x > canvas.width || ball.x < 0) {
                ball.angle = 180 - ball.angle;
                updateBall(ball);   
            } else if(ball.y > canvas.height || ball.y < 0) {
                ball.angle = 360 - ball.angle;
                 updateBall(ball);   
                //ball.draw(context);
            }

        }
        // if you want to use setInterval() instead remove next line
        setTimeout(drawScreen, 33);
    }   

    //function checkBoundaries(ball) {
        //console.log("Check Bounds: " + " " + "ball.x: " + ball.x + " " + //"ball.y: " + ball.y);

    //}

    function updateBall(ball) {
        ball.radians = ball.angle * Math.PI / 180;
        ball.dx = Math.cos(ball.radians) * ball.speed;
        ball.dy = Math.sin(ball.radians) * ball.speed;
        //ball.draw(context);
    }

  </script>
  </head>
  <body>
    <canvas id="canvas" width="600" height="480" style="background:red;"></canvas>
  </body>
</html>

http://jsfiddle.net/QVgZx/2/

于 2012-02-09T11:05:00.313 に答える
1

ここに到着したキャンバスを初めて使用する人のために、スレッドを壊して少し更新を追加します。

Stan は、コード内で各ボールを 1 つの場所に描画する関数を作成することを推奨しました。これには多くの理由があります。アニメーションがよりスムーズになり、コードのデバッグと保守がはるかに容易になります。

ただし、setInterval を使用してこれをトリガーすることに関しては、Stan には同意しません。

ただし、今は requestAnimationFrame を使用します。

これにより、ペイントがブラウザの残りの部分と同期されます。

これにより、ブラウザが何かを描画するたびに、ページ全体を再度調べて、何かが移動した場合に備えて、すべてがどこに移動するかを判断する必要があるため、コードをはるかに高速に実行できます。

setInterval を使用しても、いつ起動するかは保証されません。また、ブラウザーの画面の更新と一致するタイミングも確実にありません。

これは、少し描画し、ページを再構成し、さらに描画し、再度再構成し、さらに描画していることを意味します...そして何度も何度も。これは非常に悪く、非常に遅いです。

ただし、requestAnimationFrame を使用すると、ブラウザが画面を再描画しようとしているときにいつでも関数を呼び出すことができます。これは、1 回の再描画と 1 回の更新を意味します。

より速く、よりクリーンに。

動作は少し異なりますが、実際には非常に単純です。

requestAnimationFrame(redraw);

これにより、関数 'redraw' が requestAnimationFrame に登録され、次回ブラウザがウィンドウを再描画しようとしたときに関数が呼び出されます。

これに関する1つの問題は、関数を1回だけ呼び出すことです...そのように、setIntervalではなくsetTimeoutのようです。

この方法では、アニメーションを停止するためにタイマー変数を渡す必要はありません。呼び出されなくなったため停止します。

ただし、アニメーションが引き続き実行されるようにするには、まったく同じ呼び出しを再描画関数の最後に配置します。

function redraw()
{
    var blah, blahblah;
    ...

    requestAnimationFrame(redraw);
}

これを条件付きで設定して、アニメーションが終了するまで実行してから停止することもできます。

function redraw()
{
    ...

    if (!finished) requestAnimationFrame(redraw);
}

Mozilla リファレンスはこちら、ポール アイリッシュはこちら、クリス コイヤーはこちら

于 2013-06-29T17:43:06.467 に答える