js实现ascii图
ASCII 图生成方法
使用 JavaScript 生成 ASCII 图可以通过多种方式实现,以下是几种常见的方法:
使用字符串拼接 通过拼接字符和换行符直接构建 ASCII 图形:
const asciiArt = `
/\\_/\\
( o.o )
> ^ <
`;
console.log(asciiArt);
动态生成 ASCII 图形 对于需要程序化生成的图形,可以使用循环和条件判断:
function generatePyramid(height) {
let pyramid = '';
for (let i = 0; i < height; i++) {
pyramid += ' '.repeat(height - i - 1) + '*'.repeat(2 * i + 1) + '\n';
}
return pyramid;
}
console.log(generatePyramid(5));
使用 ASCII 艺术库
第三方库如 figlet.js 可以生成更复杂的 ASCII 艺术:
const figlet = require('figlet');
figlet.text('Hello', (err, data) => {
if (err) throw err;
console.log(data);
});
转换图像为 ASCII 图
将普通图像转换为 ASCII 图需要以下步骤:
1. 加载图像数据 使用 Canvas API 获取图像像素数据:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
convertToAscii(imageData);
};
img.src = 'image.png';
2. 像素到 ASCII 字符映射 根据亮度值选择对应字符:
function convertToAscii(imageData) {
const chars = ['@', '#', 'S', '%', '?', '*', '+', ';', ':', ',', '.'];
let ascii = '';
for (let y = 0; y < imageData.height; y++) {
for (let x = 0; x < imageData.width; x++) {
const index = (y * imageData.width + x) * 4;
const r = imageData.data[index];
const g = imageData.data[index + 1];
const b = imageData.data[index + 2];
const brightness = (r + g + b) / 3 / 255;
const charIndex = Math.floor(brightness * (chars.length - 1));
ascii += chars[charIndex];
}
ascii += '\n';
}
console.log(ascii);
}
优化 ASCII 图显示
调整字符密度 使用不同密度的字符集可以获得更好的视觉效果:
const denseChars = "@%#*+=-:. ";
const sparseChars = "@*+-. ";
添加颜色 在支持 ANSI 颜色的终端中添加颜色:
console.log('\x1b[36m' + asciiArt + '\x1b[0m');
控制宽高比 由于字符高度大于宽度,需要调整比例:
const aspectRatio = 0.5; // 字符高宽比
const scaledWidth = Math.floor(imageData.width * aspectRatio);
这些方法可以根据具体需求组合使用,生成各种复杂度的 ASCII 图形。







