HTML5上下文/画布-何时在上下文上调用draw



我正在写一个面向对象风格的javasscript演示——只是为了画一堆在屏幕上移动的球。没有什么新奇的,没有碰撞检测或任何事情。认为我的Ball.js类很好是安全的。

我的问题是:我应该在哪里叫球。draw(上下文)?按照我设置的方式将球绘制到屏幕上的唯一方法似乎是在generateBalls()中进行调用。但这意味着每个球只抽一次。

所以,如果有人能指出我在这里的错误,我真的很感激。这不是家庭作业,只是想更好地处理javascript和画布。

<!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>

谢谢你的建议,Marc

您的示例包含多个错误,请检查修改后的代码。它是有效的,但你必须扩展并更正它。

<!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/

只需坏死线程,即可为新到画布的用户添加一点更新:

Stan建议创建一个函数,在代码中的一个位置绘制每个球;这是好的,原因有很多,它使动画更流畅,代码更容易调试/维护。

然而,当谈到使用setInterval来触发这个。。。尽管如此,当斯坦写这本书的时候,这很可能是一种常见的做法

然而,现在我们使用requestAnimationFrame。

这将使您的绘画与浏览器的其他部分同步。

这让你的代码运行得更快,因为每次浏览器绘制东西时,它都必须再次浏览整个页面,以确定所有东西的去向,以防有东西移动。

使用setInterval并不能保证它何时会启动,当然也不会使它与浏览器的屏幕刷新同步。

这意味着它画了一点,重新配置页面,再画一点,再重新配置,再画一些。。。一次又一次。这非常糟糕,而且非常缓慢。

然而,使用requestAnimationFrame,浏览器可以在任何时候重新绘制屏幕时调用您的函数。。。这意味着一次重画和一次刷新。

速度快得多,清洁得多。

它的工作原理略有不同,但实际上非常简单。

requestAnimationFrame(redraw);

这会将您的函数"rewrap"注册到requestAnimationFrame中,这样下次浏览器想要重新绘制窗口时,就会调用您的函数。

问题是它只会调用你的函数一次。。。这样一来,它就像一个setTimeout,而不是一个setInterval。

这样,就不需要绕过计时器变量来停止动画;它将停止,因为它不再被调用。

然而,为了确保动画继续运行,只需将相同的调用放在重绘函数的底部即可:

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

你也可以有条件地设置它,运行你的动画直到它完成,然后停止:

function redraw()
{
    ...
    if (!finished) requestAnimationFrame(redraw);
}

Mozilla参考HERE,Paul Irish HERE和Chris Coyer HERE。

最新更新