Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

haystack-of-needles

node v14.20.1
version: 3.0.0
endpointsharetweet
const { createCanvas, loadImage } = require("canvas");
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.
exports.endpoint = function(request, response) { const count = (Math.random() * 250) >> 0; const data = generteRandomLines(200); const img = Buffer.from(data, 'base64'); response.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': img.length }); response.end(img); }
Loading…

no comments

    sign in to comment