Advertisement
stuppid_bot

ASCII ART на JavaScript

Jan 29th, 2014
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // набор символов(не более 256)
  2. glyphs = "#@&$%|!;:'`. ";
  3. // ширина и высота области, которая будет заменена на отдельный символ. Высоту берем в два раза больше ширины.
  4. width = 2;
  5. height = 4;
  6. area = width * height;
  7. // img = new Image();
  8. // img.src = '';
  9. img = document.getElementsByTagName('img')[0];
  10. canvas = document.createElement('canvas');
  11. canvas.width = img.width;
  12. canvas.height = img.height;
  13. context = canvas.getContext('2d');
  14. context.drawImage(img, 0, 0, img.width, img.height);
  15. imgData = context.getImageData(0, 0, img.width, img.height);
  16. size = imgData.width * 4;
  17. q = 256 / glyphs.length;
  18. asciiart = '';
  19. for (y = 0; y < imgData.height; y += height) {
  20.     for (x = 0; x < imgData.width; x += width) {
  21.         bs = 0;
  22.         y1 = y;
  23.         y2 = y + height;
  24.         while (y1 < y2) {
  25.             x1 = x;
  26.             x2 = x + width;
  27.             while (x1 < x2) {
  28.                 offset = x1 * 4  + y1 * size;
  29.                 bs += imgData.data[offset] * .3 + imgData.data[offset + 1] * .59 + imgData.data[offset + 2] * .11;
  30.                 ++x1;
  31.             }
  32.             ++y1;
  33.         }
  34.         asciiart += glyphs.charAt(Math.floor(bs / area / q));
  35.     }
  36.     asciiart += '\r\n';
  37. }
  38. console.log(asciiart);
  39. var link = document.createElement('a');
  40. link.setAttribute('download', 'asciiart' + new Date().getTime() + '.txt');
  41. link.href = 'data:plain/text,' + encodeURIComponent(asciiart);
  42. link.setAttribute('style', 'display: none');
  43. link.onclick = function () {
  44.     document.body.removeChild(link);
  45. };
  46. document.body.appendChild(link);
  47. link.click();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement