0

如何清除动画,使其看起来像块在移动。现在他们只是扩大,我不能让它工作 context.clearRect(0, 0, elem.width, elem.height);

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body >

    <canvas id="myCanvas" width="500" height="500" style="border:1px solid red">
            <p>Your browser doesn't support canvas.</p>
        </canvas>


</body>
</html>

<script type ="text/javascript">

    var context;

    function Shape(x, y, w, h, fill) {
        this.speedX = 1;
        this.speedY = 1;
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.fill = fill;
    }

    // get canvas element.
    var elem = document.getElementById('myCanvas');

    // check if context exist
    if (elem.getContext) {

        context = elem.getContext('2d');

        var myRect = [];

        myRect.push(new Shape(10, 0, 25, 25, "#333"))
        myRect.push(new Shape(0, 40, 39, 25, "#333"))
        myRect.push(new Shape(0, 80, 100, 25, "#333"))


            for (i in myRect) {

                //console.log(x);

                context.fillRect(myRect[i].x, myRect[i].y, myRect[i].w, myRect[i].h)

                //context.fillStyle = i.fill;
            }

            ////// x, y, width, height
            //context.fillRect(0, 0, 50, 50);

            //// x, y, width, height      
            //context.fillRect(75, 0, 50, 50);

    }

    function loop() {

        console.log('tick');



        for (i in myRect) {

            //console.log(x);


            context.fillRect(myRect[i].x, myRect[i].y, myRect[i].w, myRect[i].h)

            myRect[i].x += myRect[i].speedX;

            //context.fillStyle = i.fill;
        }


        context.clearRect(0, 0, elem.width, elem.height);  
        //context = elem.getContext('2d');


    }

    setInterval(loop, 25);

</script>
4

1 回答 1

1

在将矩形绘制到其中canvas 之前,您需要清除:

context.clearRect(0, 0, elem.width, elem.height); 
for (i in myRect) {
    context.fillRect(myRect[i].x, myRect[i].y, myRect[i].w, myRect[i].h)
    myRect[i].x += myRect[i].speedX;
}
于 2013-03-05T11:11:12.433 回答