【问题标题】:How to making rectangle in canvas html5 animated如何在画布html5中制作矩形动画
【发布时间】:2018-03-07 10:46:48
【问题描述】:

所以,我想在画布中使用矩形制作动画。当我按 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 时,它只是变为绿色,而没有查看白色矩形。有人可以帮我解释一下逻辑吗?

谢谢

【问题讨论】:

  • 您需要等待一段时间才能绘制第二个三角形,flash_white(ctx); settimeout(function() { flash_green(ctx); }, 250); 或类似的东西。
  • 什么是 250 ?它是时间变量吗?
  • 是 250 毫秒。直到函数被调用的时间。
  • 可以了,顺便说一句,是setTimeout,难怪我试了这么多次还是不行

标签: javascript html canvas html5-canvas


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 2015-10-22
    • 2018-03-20
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多