DailyJS

DailyJS

The JavaScript blog.


Tagascii
Featured

mac graphics ES6 ascii

ASCII to Vector Images

Posted on .

ASCII to vector

Charles Parnot, developer of a lab notebook application for Mac OS, recently gave a talk at NSConference about turning ASCII art into vector drawings. He's written a post about it with some awesome diagrams, entitled Replacing Photoshop With NSString:

Each shape is defined by a series of sequential characters, and a new shape is started as soon as you skip a character in the above list. So the first shape could be defined by the series ‘123456’, then the next shape with ‘89ABCDEF’, the next with ‘HIJKLMNOP’, etc. The simplest method +imageWithASCIIRepresentation:color:shouldAntialias: will draw and fill each shape with the passed color (there is also a block-based method for more options).

Earle Castledine has developed a JavaScript version called Cocoscii that can generate DOM images. The API is based around template strings:

const closeImg = cocoscii(`  
  · · · · 1 1 1 · · · ·
  · · 1 · · · · · 1 · ·
  · 1 · · · · · · · 1 ·
  1 · · 2 · · · 3 · · 1
  1 · · · # · # · · · 1
  1 · · · · # · · · · 1
  1 · · · # · # · · · 1
  1 · · 3 · · · 2 · · 1
  · 1 · · · · · · · 1 ·
  · · 1 · · · · · 1 · ·
  · · · 1 1 1 1 1 · · ·
  `, (idx, style) => {
    if (idx === 0) {
      style.fill = "#000";
    } else {
      style.stroke = "#fff";
    }
  });

The readme describes how drawing with ASCII works:

The basics are, you fill a grid with the ordered markers ... Any other characters are ignored.

If the numbers are sequential, they become a path. If you skip a number, then a new path starts. If a number is repeated twice, it becomes a line. If a number is repeated more than twice, it becomes a circle that fits inside the bounding box of all the points.

This sounds like a potentially hacker-friendly way of generating icons and simple game animations. I imagine it would be pretty easy to use it with effects like gradients and drop shadow.

Maybe there's even some way of extending the principle to something like Monodraw?

Update: There's also a Node implementation now as well! (npm: node-cocoscii)