[英]How to making rectangle in canvas html5 animated
So, I wanted to make animation using rectangle in canvas. 因此,我想使用画布中的矩形制作动画。 when I pressed Q, it change from white to green, then back again to white. 当我按Q时,它从白色变为绿色,然后又变回白色。
here is the code for rectangle green and white: 这是绿色和白色矩形的代码:
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();
}
and here is the code for the key, so when I pressed it,the box will change from green to white, then back again to green. 这是按键的代码,所以当我按下它时,此框将从绿色变为白色,然后再次变为绿色。
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);
}
in this code, when I press Q, it just change to green without viewing the white rectangle. 在此代码中,当我按Q时,它将变为绿色,而不查看白色矩形。 Can someone help me with the logic ? 有人可以在逻辑上帮助我吗?
thanks 谢谢
As Cyclone said, adding a timeout will work. 正如Cyclone所说,添加超时将起作用。
Check the code here. 在此处检查代码。
https://jsfiddle.net/billyn/awvssv98 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.