2016-01-10 67 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(); 
}