ascii

by PerroAZUL

HTML

<pre id="screen"></pre>

<pre id="guy" style="display:none"> O 
/|\
/ \</pre>

JavaScript

AsciiImage = function(id) {
    var lines = document.getElementById(id).childNodes[0].nodeValue.replace("\r", "").split("\n");
    
    this.width = lines[0].length;
    this.height = lines.length;
    this.buffer = [];
    this.buffer.length = this.width * this.height;
    
    for (var y = 0; y < this.height; y++)
        for (var x = 0; x < this.width; x++)
            this.buffer[y * this.width + x] = lines[y][x];
}

var screen = {
    width: 0,
    height: 0,
    buffer: [],
    
    initialize: function(w, h) {
        this.width = w;
        this.height = h;
        this.buffer.length = w * h;
    },
    
    clear: function(ch) {
        var size = this.width * this.height;
        for (var i = 0; i < size; i++)
            this.buffer[i] = ch;
    },
    
    put: function(image, x, y) {
        var x0 = x;
        var y0 = y;
        
        for (var y = Math.max(y0, 0); y < Math.min(y0 + image.height, this.height); y++) {
            for (var x = Math.max(x0, 0); x < Math.min(x0 + image.width, this.width); x++) {
                var imgx = x - x0;
                var imgy = y - y0;
                this.buffer[y * this.width + x] = image.buffer[imgy * image.width + imgx];
            }
        }
    },
    
    update: function() {
        var str = "";
        
        for (var y = 0; y < this.height; y++) {
            var row = "";
            
            for (var x = 0; x < this.width; x++) {
                row += this.buffer[y * this.width + x];
            }
            
            str += row + "\n";
        }
        
        $("#screen").text(str);
    }
};

var guy = new AsciiImage("guy");
guy.x = 0;
guy.y = 0;

screen.initialize(50, 30);

setInterval(function() {
    guy.x = (guy.x + 1) % screen.width;
    screen.clear(".");
    screen.put(guy, guy.x, guy.y);
    screen.update();
}, 16);