2013-03-05 98 views
0

如何清除動畫,使其看起來像塊正在移動。現在,他們只是擴大和我不能得到這個工作context.clearRect(0, 0, elem.width, elem.height);html5如何清除此動畫的畫布?

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

回答

1

你需要清除canvas之前,您繪製rectangulars到它:

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; 
}