Skip to content

Instantly share code, notes, and snippets.

@gonejack
Created September 29, 2024 11:25
Show Gist options
  • Save gonejack/556a2a56e00348a09123db98b56f6ed3 to your computer and use it in GitHub Desktop.
Save gonejack/556a2a56e00348a09123db98b56f6ed3 to your computer and use it in GitHub Desktop.
网页模拟点阵屏
<!doctype html>
<html lang="en">
<body style="background-color: black;">
<div id="screen" style="display: flex; justify-content: center; align-items: center; height: 80vh"></div>
<script>
class TextPointSet {
constructor() {
this.points = {};
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');
}
getChar(char) {
return this.points[char] || this._createTextPoint(char);
}
getAll(text) {
return text.split('').map(char => this.getChar(char));
}
_createTextPoint(text) {
const size = 15;
this.clearCanvas();
this.canvas.width = this.canvas.height = size;
this.ctx.font = `${size}px GB18030 Bitmap`;
this.ctx.fillText(text, 0, 15);
const canvasData = this.ctx.getImageData(0, 0, size, size).data;
const textPointSet = [];
for (let i = 0; i < size; i++) {
const row = [];
for (let j = 0; j < size; j++) {
const index = i * size * 4 + j * 4;
const alpha = canvasData[index + 3];
row.push(alpha ? 1 : 0);
}
textPointSet.push(row);
}
return (this.points[text] = textPointSet);
}
clearCanvas() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
getCanvas(points, options = {size: 100, pointScale: 0.2}) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const length = points.length;
const oneTempLength = options.size / length;
canvas.width = canvas.height = options.size;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
ctx.fillStyle = points[i][j] ? "yellow" : "rgb(50,50,50)";
ctx.beginPath();
ctx.arc(
oneTempLength * (j + 0.5),
oneTempLength * (i + 0.5),
oneTempLength * options.pointScale,
0,
Math.PI * 2
);
ctx.closePath();
ctx.fill();
}
}
return canvas;
}
getCanvasWithText(char, options) {
return this.getCanvas(this.getChar(char), options);
}
}
const textSet = new TextPointSet();
textSet.getAll('模拟点阵屏的例子').map(points => {
document.getElementById("screen").appendChild(textSet.getCanvas(points, {size: 100, pointScale: .3}));
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment