我想用Canvas制作一个textadventure,并且解析器应该像Dos控制台中的解析器一样永久闪烁。解析器保存为全局变量。我该怎么做才能永久地通过jQuery更改全局变量的字符?
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
string = '', //Empty string which combines command, parser and '>' character
start_cmd ='>', //The character '>' starts before the command
command = '', //Typed characters
parser = '_'; //Parser which appears at the end of 'command'
$(document).on('keypress', function(event) {
string = start_cmd + command + parser;
$(document).clear(); //Self declared function which makes the whole canvas white.
$(document).drawConsole(); //Self declared function which draws the console.
$(document).println(string, 10, 550);//Self declared function which writes what you last typed in the keyboard.
switch (event.which)
{
case 8:
command = command.slice(0, -1);
$(document).clear();
$(document).drawConsole();
break;
case 13:
command = '';
$(document).clear();
$(document).drawConsole();
break;
default:
if (command.length < 46)
{
$(document).clear();
$(document).drawConsole();
command += String.fromCharCode(event.which);
}
break;
}
string = start_cmd + command + parser;
$(document).println(string, 10, 550);
console.log(event.which);
});
});
答案 0 :(得分:1)
实现此目标的最佳位置可能在您的println()
方法中。您可以创建一个时间间隔来删除字符串中的最后一个字符 - 它始终是_
,或者添加它。
let visible = true;
setInterval(() => {
let t = document.getElementById('foo');
visible = !visible;
t.innerText = visible ? t.innerText.trim().slice(0, -1) : (t.innerText + "_");
}, 200);
<div id="foo">
foo
</div>