简体   繁体   中英

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.

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. Can someone help me with the logic ?

thanks

As Cyclone said, adding a timeout will work.

Check the code here.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM