動的なOGPを生成する
コードはここ
https://github.com/itizawa/penguin-ogp external_link
成果物はここ
https://penguin-ogp.vercel.app/api/ogp?text=こんにちは人類 external_link
text を query で渡して、その文字列を合成して表示する
ひとまず hello の表示
const { createCanvas } = require("canvas"); export default async (req, res) => { const canvas = createCanvas(600, 315); const context = canvas.getContext("2d"); context.font = "15px myfont"; context.fillStyle = "#424242"; context.fillText("hello", 100, 100); const image = canvas.toBuffer(); res.writeHead(200, { "Content-Type": "image/png", "Content-Length": image.length, }); res.end(image, "binary"); };
__dirname とは
The directory name of the current module. This is the same as the path.dirname() of the __filename.
ディレクトリ名までを取得できる。
path.join を使って 背景画像の表示
path.join(__dirname,"..","images","background.png");
js:// Add background const backgroundImage = await loadImage(BACKGROUND_IMAGE_PATH); context.drawImage(backgroundImage, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
読み込みはこんな感じ
font 読み込みを忘れない
const FONT_FAMILY = "rounded-mplus-1p-medium"; const FONT_PATH = path.join( __dirname, "..", "fonts", "rounded-mplus-1p-medium.ttf" ); registerFont(FONT_PATH, { family: FONT_FAMILY });
参考
https://github.com/retoruto-carry/shindan-chart-maker-ogp external_link