gpt4 book ai didi

javascript - 将 setTimeout 与 Canvas 结合使用以打印数组中的文本

转载 作者:行者123 更新时间:2023-11-29 16:13:09 25 4
gpt4 key购买 nike

你好,程序员:

我希望将数组中的一系列字符串打印到 Canvas 上。目前,它不会清除 Canvas 在单次迭代中打印所有文本。

var test1 = ["This","is","a","test","to","see","if","it","really","works"];

function printWord(i){
setTimeout( function(){ ctx.fillText(test1[i], 150, 90) }, 1000 ) }

function clearScreen(){
ctx.clearRect(0, 0, 300, 100);
}

function playText(){
for(var i = 0; i < test1.length; i++){
clearScreen;
printWord(i);
};
}
playText();

这是 JSFiddle .更新了链接,感谢 Bigood 修复了时间。仍然需要帮助清理 Canvas 。

谢谢,

LLCreatini

最佳答案

你的问题是你的循环一次调用所有这些超时,而不是延迟调用。相反,您需要一个间隔,然后在完成数组后将其清除(我从中获得了一些灵感:setTimeout inside for loop)。这是一个修改后的示例,使用与我发布的链接相同的方法:

var test1 = ["This","is","a","test","to","see","if","it","really","works."];

var c = document.getElementById("screen"); //Setup screen.
var ctx = c.getContext("2d");
ctx.font = "normal 42px Arial";
ctx.textAlign= "center";
var i = 0;

function clearScreen(){
ctx.clearRect(0, 0, 300, 100);
}

var timer = setInterval(function(){
clearScreen();
ctx.fillText(test1[i], 150, 91);
i++;
if(i >= test1.length) {
clearInterval(timer);
}
}, 200);

timer();

这是工作 JSFiddle 的链接

关于javascript - 将 setTimeout 与 Canvas 结合使用以打印数组中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22354601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com