Last active
November 14, 2020 02:08
-
-
Save suraneti/d943c653fe97444fa70294bad0bdb4d3 to your computer and use it in GitHub Desktop.
Canvas to chunk btyes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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