简体   繁体   English

html5如何清除此动画的画布?

[英]html5 how do I clear the canvas for this animation?

How do I clear the animation so that It looks like the blocks are moving. 如何清除动画,以便看起来像块在移动。 Right now they just expand and I cant get this to work context.clearRect(0, 0, elem.width, elem.height); 现在,它们只是扩展context.clearRect(0, 0, elem.width, elem.height);我无法使其正常运行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>

You need to clear the canvas before you draw your rectangulars into it: 将矩形绘制到canvas 之前,需要清除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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM