Skip to content

Instantly share code, notes, and snippets.

@suraneti
Last active November 14, 2020 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suraneti/d943c653fe97444fa70294bad0bdb4d3 to your computer and use it in GitHub Desktop.
Save suraneti/d943c653fe97444fa70294bad0bdb4d3 to your computer and use it in GitHub Desktop.
Canvas to chunk btyes
const { createCanvas } = require("canvas");
class Canvas {
createImage() {
const width = 200;
const height = 200;
const canvas = createCanvas(width, height);
const context = canvas.getContext("2d");
context.fillStyle = "#000";
context.fillRect(0, 0, width, height);
context.font = "30px Impact";
context.textAlign = "center";
context.textBaseline = "top";
context.fillStyle = "#3574d4";
const text = "Hello World!";
context.fillText(text, 20, 20);
const buffer = canvas.toBuffer();
return buffer;
}
chunkBytes(s, maxBytes) {
let buf = Buffer.from(s);
const result = [];
while (buf.length) {
let i = buf.lastIndexOf(32, maxBytes + 1);
// If no space found, try forward search
if (i < 0) i = buf.indexOf(32, maxBytes);
// If there's no space at all, take the whole string
if (i < 0) i = buf.length;
// This is a safe cut-off point; never half-way a multi-byte
result.push(buf.slice(0, i).toString());
buf = buf.slice(i + 1); // Skip space (if any)
}
return result;
}
print(arrayBytes) {
for (let i = 0; i < arrayBytes.length; i++) {
await printCharacteristic.writeValue(arrayBytes[i])
}
}
}
const canvas = new Canvas();
const buffer = canvas.createImage();
const chunkBytes = canvas.chunkBytes(buffer, 512);
canvas.print(chunkBytes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment