# 動的なOGPを生成する

## コードはここ
https://github.com/itizawa/penguin-ogp

## 成果物はここ
https://penguin-ogp.vercel.app/api/ogp?text=こんにちは人類  
text を query で渡して、その文字列を合成して表示する
## ひとまず hello の表示

```js
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");`

```ogp.js: js
// Add background
const backgroundImage = await loadImage(BACKGROUND_IMAGE_PATH);
context.drawImage(backgroundImage, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
```
読み込みはこんな感じ



## font 読み込みを忘れない

```js
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

![image.png](/attachment/5f007e8bb1893100488d2b1e)



---

## Page Navigation

- Canonical URL: https://tips.weseek.co.jp/WSもくもく会/20200704/動的なOGPを生成する
- Permalink: https://tips.weseek.co.jp/5f0038c329b73000484ddde2
- Parent: [20200704](/5f00101129b73000484dddb4.md)
- Children: 0 total
- Total descendants: 0
- Siblings: 0 total
- Last updated: 2020-07-11T07:09:43.075Z by deleted_at_1672138397219
- Full page listing (all children regardless of count): https://tips.weseek.co.jp/_api/v3/page-listing/children?id=5f0038c329b73000484ddde2
