Built with blockbuilder.org
forked from biovisualize's block: Chinese ascii fork from @enjalot
license: mit |
Built with blockbuilder.org
forked from biovisualize's block: Chinese ascii fork from @enjalot
<!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://avatars.githubusercontent.com/u/1466175?v=4" | |
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> |