|
| 1 | +const { Worker, isMainThread, workerData, parentPort } = require('worker_threads') |
| 2 | +const fs = require('fs') |
| 3 | +const path = require('path') |
| 4 | + |
| 5 | +const ARIMO = path.join(__dirname, '../test/fixtures/Arimo-Regular.ttf') |
| 6 | +const PFENNIG = path.join(__dirname, 'pfennigFont/Pfennig.ttf') |
| 7 | +const BADGE = path.join(__dirname, 'images/badge.svg') |
| 8 | + |
| 9 | +const WORKERS = [ |
| 10 | + { index: 0, color: '#1a1a2e', fonts: ['arimo'], useFont: 'Arimo', svg: false }, |
| 11 | + { index: 1, color: '#16213e', fonts: ['arimo'], useFont: 'Arimo, Pfennig', svg: false }, |
| 12 | + { index: 2, color: '#0f3460', fonts: ['arimo', 'pfennig'], useFont: 'Arimo', svg: true }, |
| 13 | + { index: 3, color: '#533483', fonts: ['arimo', 'pfennig'], useFont: 'Pfennig', svg: true } |
| 14 | +] |
| 15 | + |
| 16 | +if (isMainThread) { |
| 17 | + let done = 0 |
| 18 | + |
| 19 | + for (const config of WORKERS) { |
| 20 | + const worker = new Worker(__filename, { workerData: config }) |
| 21 | + |
| 22 | + worker.on('message', ({ index, buffer }) => { |
| 23 | + const file = path.join(__dirname, `worker-${index}.png`) |
| 24 | + fs.writeFileSync(file, buffer) |
| 25 | + console.log(`Wrote ${file}`) |
| 26 | + if (++done === WORKERS.length) console.log('All workers done.') |
| 27 | + }) |
| 28 | + |
| 29 | + worker.on('error', (err) => { |
| 30 | + console.error(`Worker ${config.index} error:`, err) |
| 31 | + }) |
| 32 | + } |
| 33 | +} else { |
| 34 | + const { createCanvas, FontFace, fonts, loadImage } = require('..') |
| 35 | + const { index, color, fonts: fontNames, useFont, svg } = workerData |
| 36 | + |
| 37 | + if (fontNames.includes('arimo')) fonts.add(new FontFace('Arimo', ARIMO)) |
| 38 | + if (fontNames.includes('pfennig')) fonts.add(new FontFace('Pfennig', PFENNIG)) |
| 39 | + |
| 40 | + const render = async () => { |
| 41 | + const canvas = createCanvas(200, 200) |
| 42 | + const ctx = canvas.getContext('2d') |
| 43 | + |
| 44 | + ctx.fillStyle = color |
| 45 | + ctx.fillRect(0, 0, 200, 200) |
| 46 | + |
| 47 | + if (svg) { |
| 48 | + const badge = await loadImage(BADGE) |
| 49 | + ctx.drawImage(badge, 10, 10, 80, 80) |
| 50 | + } |
| 51 | + |
| 52 | + ctx.fillStyle = 'white' |
| 53 | + ctx.font = `bold 26px ${useFont}` |
| 54 | + ctx.textAlign = 'center' |
| 55 | + ctx.textBaseline = 'middle' |
| 56 | + ctx.fillText(`Worker ${index}`, 100, 110) |
| 57 | + |
| 58 | + ctx.font = `13px ${useFont}` |
| 59 | + ctx.fillText(`${useFont} / [${fontNames.join(', ')}]`, 100, 140) |
| 60 | + |
| 61 | + return canvas.toBuffer('image/png') |
| 62 | + } |
| 63 | + |
| 64 | + render().then(buffer => parentPort.postMessage({ index, buffer })) |
| 65 | +} |
0 commit comments