Built with blockbuilder.org
Created
January 23, 2016 08:34
-
-
Save biovisualize/3a9d6b3688cd1bfeb35e to your computer and use it in GitHub Desktop.
Chinese ascii fork from @enjalot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
svg { width:100%; height: 100% } | |
#ascii { | |
font-size: 6px; | |
font-family: monospace; | |
line-height: 1em; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="base-image"></canvas> | |
<div id="container"> | |
<pre id="ascii"></pre> | |
</div> | |
<script> | |
var ascii = document.getElementById("ascii"); | |
var canvas = document.getElementById('base-image'); | |
var ctx = canvas.getContext('2d'); | |
var link = 'https://lh3.googleusercontent.com/-EJb9d9opnOc/T0XJ9oHISiI/AAAAAAAAA_0/iyxZALNns68/s182-Ic42/christophe_portrait_square.jpg'; | |
var asciiScale = d3.scale.ordinal() | |
.domain(['我', '你', "大", "一" ,"。"]) | |
.range([0, 50, 121, 200, 255]) | |
var width, height; | |
var outputResolution = 64; | |
var img = new Image(); | |
img.onload = function(){ | |
var outputH = outputResolution * img.height / img.width; | |
canvas.width = outputResolution; | |
canvas.height = outputH; | |
ctx.drawImage(img, 0, 0, outputResolution, outputH); | |
var data = ctx.getImageData(0, 0, outputResolution, outputH); | |
render(data) | |
} | |
img.crossOrigin = ''; | |
img.src = link; | |
function render(pixels){ | |
var colordata = pixels.data; | |
asciiScale.invert = function(x){ | |
return this.domain()[d3.bisect(this.range(), x) - 1]; | |
} | |
var r, g, b, gray; | |
var character, line = ''; | |
for(var i = 0; i < colordata.length; i = i+4){ | |
r = colordata[i]; | |
g = colordata[i+1]; | |
b = colordata[i+2]; | |
//converting the pixel into grayscale | |
gray = r*0.2126 + g*0.7152 + b*0.0722; | |
//text for ascii art. | |
//blackish = dense characters like "W", "@" | |
//whitish = light characters like "`", "." | |
character = asciiScale.invert(gray); | |
//newlines and injection into dom | |
if(i != 0 && (i/4)%outputResolution == 0){ //if the pointer reaches end of pixel-line | |
ascii.appendChild(document.createTextNode(line)); | |
//newline | |
ascii.appendChild(document.createElement("br")); | |
//emptying line for the next row of pixels. | |
line = ""; | |
} | |
line += character; | |
} | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment