Created
May 20, 2011 19:28
-
-
Save cxx/983602 to your computer and use it in GitHub Desktop.
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
// ==UserScript== | |
// @name Show Kanji Image | |
// @namespace http://gyz.heroku.com/ | |
// @include http://twitter.com/* | |
// @include https://twitter.com/* | |
// @version 1.0.2 | |
// ==/UserScript== | |
var $ = function(selectors, context) { | |
return Array.prototype.slice.call((context || document).querySelectorAll(selectors), 0); | |
}; | |
var showImage = function () { | |
$('.tweet-text').forEach(function(elem) { | |
if ($('canvas', elem).length > 0) return; | |
var match = elem.textContent.match(/(k-host\.appspot\.com\/)?([\u4e00-\u8dff]{109,124})/); | |
if (!match) return; | |
var text = match[2]; | |
var cols = 18; | |
var scale = 16; | |
var dataLen = text.length; | |
var bodyLen = (cols / 3) * cols; | |
var paletteLen = dataLen - bodyLen; | |
var data = []; | |
for (var i = 0; i < dataLen; i++) | |
data.push(text.charCodeAt(i) - 0x4e00); | |
var palette = data.slice(0, paletteLen).map(function(val) { | |
var r = (val >> 6) & 0xf8; r |= r >> 5; | |
var g = (val >> 1) & 0xf8; g |= g >> 5; | |
var b = (val << 4) & 0xf0; b |= b >> 4; | |
return 'rgb('+[r, g, b].join(', ')+')'; | |
}); | |
var p = document.createElement('p'); | |
var canvas = document.createElement('canvas'); | |
canvas.height = canvas.width = cols*scale; | |
p.appendChild(canvas); | |
elem.appendChild(p); | |
var ctx = canvas.getContext('2d'); | |
ctx.scale(scale, scale); | |
var comment = []; | |
var commentLen = parseInt(bodyLen / 8) * 8; | |
i = 0; | |
data.slice(paletteLen).forEach(function(val) { | |
for (var j = 8; j >= 0; j -= 4, i++) { | |
ctx.fillStyle = palette[(val >> j) & 0x0f]; | |
ctx.fillRect(parseInt(i%cols), parseInt(i/cols),1,1); | |
} | |
comment.push(val >> 12) | |
}); | |
if (match[1]) { | |
var a = document.createElement('a'); | |
a.href = 'http://' + match[0]; | |
a.target = '_blank'; | |
a.textContent = match[0]; | |
elem.replaceChild(a, elem.firstChild); | |
} | |
if (comment.some(function(n) { return n > 0; })) { | |
var commentStr = ''; | |
while (comment.length >= 8) { | |
var n = 0; | |
for (i = 0; i < 8; i++) | |
n = (n << 2) | comment.shift(); | |
commentStr += String.fromCharCode(n); | |
} | |
p = document.createElement('p'); | |
p.style.fontSize = '100px'; | |
p.textContent = commentStr; | |
elem.appendChild(p); | |
} | |
}); | |
}; | |
document.addEventListener('DOMNodeInserted', showImage, false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment