2011-06-25 59 views
2

我想要一個矩形水平移動..但是,矩形不是動畫..我該如何解決這個問題?如何製作此動畫?

<script type="text/javascript"> 
var interval = 10; 
var x=0; 
var y=0; 
var rect = null; 
var context ; 
var canvas; 

function Rectangle(x, y, width, height, borderWidth) { 
    this.x=x; 
    this.y=y; 
    this.width = width; 
    this.height = height; 
    this.borderWidth = borderWidth; 
} 

function DrawRects(){ 
    myRectangle = new Rectangle (250,70,100,50, 5); 

    context.rect(myRectangle.x,myRectangle.y,myRectangle.width,myRectangle.height) 
    context.fillStyle="#8ED6FF"; 
    context.fill(); 
    context.lineWidth=myRectangle.borderWidth; 
    context.strokeStyle="black"; 
    context.stroke(); 
} 

function updateStageObjects() { 
    var amplitude = 150; 
    var centerX = 240;  
    var nextX = myRectangle.x+ 10; 

    myRectangle.x = nextX;  
} 

function clearCanvas() { 
    context.clearRect(0,0,canvas.width, canvas.height); 
} 

function DrawRect(){ 
    alert("Test1"); 
    setTimeout(CheckCanvas,10); 

    //clearCanvas(); 

    updateStageObjects(); 

    DrawRects(); 
    alert("Test2"); 
} 

function CheckCanvas(){ 
    return !!(document.createElement('canvas').getContext); 
} 

function CheckSound(){ 
    return !!(document.createElement('sound').canPlayType) 
} 

function CheckVideo(){ 
    return !!(document.createElement('video').canPlayType) 
} 

function Checkstorage(){ 
    return !!(window.localStorage) 
} 

function CheckVideo(){ 
    return !!(document.createElement('video').canPlayType) 
} 

function DrawCanvas(){ 
    if (CheckCanvas()){ 
    canvas = document.getElementById('Canvas'); 
    context =canvas.getContext('2d'); 

    $('#Result').text('Canvas supported...'); 
    $('#Result').text($('#Result').text()+'Sound supported...'+CheckSound()); 
    $('#Result').text($('#Result').text()+'Video supported...'+CheckVideo()); 
    $('#Result').text($('#Result').text()+'Storage supported...'+Checkstorage()); 

    DrawRects(); 
    setInterval(DrawRect(), 10); 
    } 
} 
</script> 

HTML:

<canvas id="Canvas" width="800px" height="800px" onclick="DrawCanvas()"> Nor supported</canvas> 
+0

你看到了什麼行爲?你有沒有試過調試這段代碼? –

+1

一旦執行完所有的調用並暫停,它就進入DrawRect()。設置的時間間隔似乎不會間隔地調用該函數,只調用一次。 –

+0

http://jsfiddle.net/zCEyH/ –

回答

4

你需要做的

setInterval(DrawRect, 10); 

使用DrawRect()將調用函數一次,然後再嘗試調用結果是功能,作爲函數(不是)每10毫秒。