[英]How to making rectangle in canvas html5 animated
因此,我想使用畫布中的矩形制作動畫。 當我按Q時,它從白色變為綠色,然后又變回白色。
這是綠色和白色矩形的代碼:
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時,它將變為綠色,而不查看白色矩形。 有人可以在邏輯上幫助我嗎?
謝謝
正如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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.