Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - Ascii Art Animation in Browser

I want to animate Ascii Art in the Browser. The Ascii Art should be loaded via a text file. There are many libraries which convert but I have found none, which actually animates it.

By animation I mean a typewriter animation that speeds up over time and changes the 'zoom factor' so that the whole image is visible in the viewport at the end.

Hopefully anyone knows a libary for my problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have a feeling SO doesn't like library recommendations, and actually I haven't found one, so here's some basic code to get you started.

It sets the typing speed to the old Teletype 10 chars per second and of course that can be changed, and an acceleration function can be added when you know what you want for that. Note: the txt file needs to be on the same domain to prevent CORS problems.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Typewriter print</title>
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  font-family: Courier, monospace;
  font-size: 12px;
}
</style>
</head>
<body>
<div id="container">
    <input id="file" type="text" value=""  placeholder="Filename" /><button  onclick="loadFile()">Click to draw the file</button>
    <div id="picture"></div>
</div>
<script>
let file = '';
let reader = new XMLHttpRequest();

function loadFile() {
    file = document.getElementById('file').value;
    reader.open('get', file, true); 
    reader.onreadystatechange = draw;
    reader.send(null);
}

function draw() {
    if(reader.readyState==4) {
        const picture = document.getElementById('picture');
        picture.innerHTML = '';
        let str = reader.responseText;
        let chs = str.split('');
        let chsPerSec = 10; //set as the typing speed in characters per second 10 is the old teletype speed
        let i = 0;
        function reveal() {
          if (i<chs.length) {
            let nextch = chs[i];
            if (nextch.charCodeAt(0) == 10) {nextch = '<br>';}
            else if (nextch.charCodeAt(0) == 32) {nextch = '<span style="color:transparent;">.</span>';}
            picture.innerHTML = picture.innerHTML + nextch;
            setTimeout(reveal, Math.floor(1000/chsPerSec));
            i++;
          }
        }
        reveal();
    }
}

</script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...