Camera ASCII
Camera ASCII uses the HTML5 getUserMedia
API to transform a video stream from your webcam into a real-time ASCII representation. You can use the library without camera, you can generate the same effect drawing a image on a canvas.
The demo works using 2 plugins, camera.js (a wrapper to get acces to the camera and display it on a canvas) and ascii.js, the most important piece of the demo. ascii.js is a tiny library that converts a canvas image to an art string.
How does it works
The library returns a global object named ascii , this object has only 1 property "fromCanvas". This function expects as first parameter the canvas which is going to be processed and as second parameter an object with the properties.
var canvas = document.getElementById("myCanvasId");
ascii.fromCanvas(canvas, {
callback: function(asciiString) {
// Do something with the asciiString
}
});
The library will use the following characters in the ascii string ".,:;i1tfLCG08@".
var characters = (" .,:;i1tfLCG08@").split("");
var context = canvas.getContext("2d");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var asciiCharacters = "";
// calculate contrast factor
// http://www.dfstudios.co.uk/articles/image-processing-algorithms-part-5/
var contrastFactor = (259 * (options.contrast + 255)) / (255 * (259 - options.contrast));
var imageData = context.getImageData(0, 0, canvasWidth, canvasHeight);
Then it will use a loop with the retrieved pixel data using the getImageData
function from the canvas and according to the brightness of every pixel (Color brightness is determined by the following formula: ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000
) a character from the characters
variable will be choosen to be drawn (appended to the asciiCharacters
variable).
Note: the contrast of the image will be changed to get a better result, you can increment the contrast using the contrast parameter in the fromCanvas function.
Demo
You can test a live version from the plugin here.
Note that you can use css to customize and give curious effects to the image. The previous image has been rendered using css : color:blue;
to the pre element.
You can customize to changing the characters that are being rendered, for example :
The previous image has been achieved changing the characters line in the ascii.js file:
var characters = {
0:'<span style="background-color: yellow;"> </span>',
1:".",
2:",",
3:":",
4:";",
5:"i",
6:"1",
7:"t",
8:"f",
9:"L",
10:"C",
11:"G",
12:"0",
13:"8",
14:'<span style="color: red;">@</span>'
}
Note that the performance will decrease noticeably if you're using the camera instead of a image on a canvas.
Requirements
- Your navigator needs to provide support for getUserMedia API
- https connection as insecure connections doesn't allow access to the API
Have fun !