2016-01-10 68 views
0

所以,我想在畫布上使用矩形制作動畫。當我按下Q時,它會從白色變成綠色,然後再變回白色。如何在畫布中製作矩形html5動畫

這裏是矩形,綠色和白色的代碼:

function flash_green(ctx) 
{ 
ctx.strokeStyle="red"; 
ctx.fillStyle="green"; 
ctx.strokeRect(150,125,190,70); 
ctx.fillRect(150,125,190,70); 
ctx.stroke(); 
} 

function flash_white(ctx) 
{ 
ctx.strokeStyle="red"; 
ctx.fillStyle="white"; 
ctx.strokeRect(150,125,190,70); 
ctx.fillRect(150,125,190,70); 
ctx.stroke(); 
} 

這裏是關鍵代碼,所以當我按下它,該框由綠色變爲白色,然後再回到變爲綠色。

window.addEventListener("keypress",onKeyPress); 
function onKeyPress(e) 
{ 
    console.log(e.keyCode); 
    var str = String.fromCharCode(e.keyCode); 
    console.log(str+":"+e.keyCode); 
    var tune = new Audio(); 


    if (e.keyCode == 113) 
    { 
     tune = new Audio("Assets/Tune/C.mp3"); 
     tune.play(); 
     stringTuts = "C"; 
     stringKey = "Q"; 
     showText(stringTuts,stringKey); 
     flash_white(ctx); 
     flash_green(ctx); 
    } 

在這段代碼中,當我按Q時,它只是變成綠色而沒有查看白色矩形。有人能幫我理解邏輯嗎?

謝謝

+1

你需要繪製你第二個三角形,'flash_white(CTX)之前等待一段時間; settimeout(function(){flash_green(ctx);},250);'或類似的東西。 – Cyclonecode

+0

什麼是250?它的時間變量? –

+0

是250毫秒。直到函數被調用的時間。 – Cyclonecode

回答

1

正如Cyclone所說,增加一個超時會有效。

查看此處的代碼。

https://jsfiddle.net/billyn/awvssv98

window.addEventListener("keypress", onKeyPress); 

var c = document.getElementById("myCanvas"); 
var ctx = c.getContext("2d"); 

function onKeyPress(e) { 
    var str = String.fromCharCode(e.keyCode); 

    if (e.keyCode == 113) { 
    flash_green(ctx); 
    setTimeout(function(){flash_white(ctx)}, 1000); // First 
    setTimeout(function(){flash_green(ctx)}, 1500); // Second 
    } 
} 

function flash_green(ctx) { 
    ctx.strokeStyle="red"; 
    ctx.fillStyle = "green"; 
    ctx.strokeRect(0, 0, 190, 70); 
    ctx.fillRect(0, 0, 190, 70); 
    ctx.stroke(); 
} 

function flash_white(ctx) { 
    ctx.strokeStyle = "red"; 
    ctx.fillStyle = "white"; 
    ctx.strokeRect(0, 0, 190, 70); 
    ctx.fillRect(0, 0, 190, 70); 
    ctx.stroke(); 
}