It’s been a while since I coded something up that I had both a challenge and fun doing. I was giving a html5 lesson to a friend and we were looking at the videostream to capture a snapshot of a video.
I started messing with it and once I had the pixels read into a HTML5 canvass you can do some pretty cool stuff because you can find out the colour of each pixel and redraw them one by one if necessary.
I had seen other video to ascii demos out there but wanted to implement my own from scratch to see if I could do it for both fun and a challenge.
Here’s what I did for those interested:
- First I put in place the HTML code to capture HTML5 video stream from a video element
- I also create a canvas to draw frames from this video to
- On the canvas on start up I draw out visible ASCII characters from space (32) to 127
- I interrogate each character to find out how bright they are and sorted them by brightness
- I then chose 16 characters from this list at intervals from most dim (space) to most bright. In courier font this seems to be the M character. I keep this as my ASCII pixel set for use later.
- I then implemented a timer (using setInterval) to capture the video stream to a HTML5 canvas every 1/10th of a second
- I interrogate the canvass in block sizes that match the characters I will eventually output
- I convert each pixel to greyscale and work out an average brightness for the entire block and divide this by 16 to get a 16 colour representation of the block.
- I then wipe that block from the canvas so that I can then output the character that represents this level of brighness (see point 5) at that position
That’s pretty much it, nothing spectactular. The code is a bit sluggish depending on what browser you have and the beef of your machine. I’m sure it can be made more efficient but I don’t have that much time on my hands.