NodeJS is a backend server, the heart of the Chrome browser with out the typical browser APIs, this means we have to lean on an exteral library to use `canvas`
function generteRandomLines(count = 150, x = 1300, y = 200) {
const canvas = createCanvas(x, y);
const ctx = canvas.getContext("2d");
// Write "Awesome!"
ctx.font = "900 18px Arial, sans-serif";
const date = new Date().toString().split(" ").slice(0, 5);
const text = `Random lines: ${count} - Date: ${date}`;
ctx.textAlign = "center";
ctx.fillText(text, x / 2, y - 20);
// Draw line under text
for (var i = 0; i < count; i++) {
ctx.beginPath();
const points = [
(Math.random() * x) >> 0,
(Math.random() * y) >> 0,
(Math.random() * x) >> 0,
(Math.random() * y) >> 0,
];
const [x1, y1, x2, y2] = points;
ctx.lineTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// remove the content type prefix ie. data:image/png;base64,
return canvas.toDataURL().replace(/^(data[^,]+,)/, "");
}
# generteRandomLines()
this function creates our haystack and adds a date timestamp so when the image is reloaded the time is obvious
the function returns a base64 string BUT the important thing to notice here is the last line.
Buffer.from(generteRandomLines(), 'base64');
`canvas.toDataURL()` gives us a data URL that includes the content-type as a string prefix.
For example: `data:image/png;base64,iVBORw0KGgoAAA........Abcd===`
We MUST remove the prefix from the return value because it will corrupt the server response.