展示
源码
ul {
list-style: none;
margin: 0;
padding: 0;
&::after,
&::before {
content: '';
clear: both;
display: block;
}
li {
float: left;
width: 2px;
height: 2px;
}
}
<canvas id="canvas"></canvas>
<div id="image-wrap"></div>
// 初始化图片
let image = new Image();
image.src = './00.png';
image.onload = () => {
const el = document.getElementById('canvas');
draw(el, 1);
}
/**
* 绘制图片到canvas中 并转换为html
* el canvas标签
* vivid 清晰度,数值越小越清楚
*/
const draw = (el,) => {
const w = el.width = image.width;
const h = el.height = image.height;
const ctx = el.getContext('2d');
ctx.drawImage(image, 0, 0, w, h);
// 像素数据
const imageData = ctx.getImageData(0, 0, w, h).data;
// 图片转HTML
document.getElementById('image-wrap').innerHTML = imageToHtml(imageData, w, h, vivid);
// 图片转字符串
console.log(imageToStr(imageData, w, h, vivid));
}
// 图片转HTML
const imageToHtml = (data, w, h,) => {
var html = '';
for (let row = 0; row < h; row += vivid) {
html += '<ul>';
for (let col = 0; col < w; col += vivid) {
// 第row行第col个像素点的rgba 跨度为vivid个点
let rgba = data.slice((row * w + col) * 4, (row * w + col) * 4 + 4);
// console.log("%c点",`background:rgba(${rgba.join(',')})`);
html += `<li style="background: rgba(${rgba.join(',')});"></li>`;
}
html += '</ul>';
}
return html;
};
// 图片转字符串
const imageToStr = (data, w, h,) => {
var str = '';
for (let row = 0; row < h; row += vivid) {
str += '\n';
for (let col = 0; col < w; col += vivid) {
// 第row行第col个像素点的rgba 跨度为vivid个点
let rgba = data.slice((row * w + col) * 4, (row * w + col) * 4 + 4);
// console.log("%c点",`background:rgba(${rgba.join(',')})`);
// #深色 -浅色
var deep = rgba[0] * 0.299 + rgba[1] * 0.587 + rgba[2] * 0.114;
if (deep >= 50) {
str += '-';
} else {
str += '#';
}
}
}
return str;
};