83
loading...
This website collects cookies to deliver better user experience
npx create-next-app --ts
yarn add [email protected]
fonts/
pages/
├ api/
│ └ ogi.ts
├ [id]/
│ └ index.tsx
└ index.tsx
// api/ogi.ts
const createOgi = async (
req: NextApiRequest,
res: NextApiResponse
): Promise<void> => {
const { id } = req.query;
const WIDTH = 1200 as const;
const HEIGHT = 630 as const;
const canvas = createCanvas(WIDTH, HEIGHT);
const ctx = canvas.getContext("2d");
registerFont(path.resolve("./fonts/NotoSansJP-Regular.otf"), {
family: "Noto",
});
ctx.fillStyle = "#FFF";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.font = "60px ipagp";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const text = "入力した文字は" + String(id) + "なのねん";
ctx.fillText(text, WIDTH / 2, HEIGHT / 2);
const buffer = canvas.toBuffer();
res.writeHead(200, {
"Content-Type": "image/png",
"Content-Length": buffer.length,
});
res.end(buffer, "binary");
}
export default createOgi;
yarn dev
and look at http://localhost:3000/api/ogi?id=hoge. If the image is created like below, succeeded.<Head> tags
easily.// pages/[id]/index.tsx
import React from "react";
import { GetServerSidePropsContext, GetServerSidePropsResult } from "next";
import Head from "next/head";
type Props = {
id: string;
};
export const getServerSideProps = async (
context: GetServerSidePropsContext
): Promise<GetServerSidePropsResult<Props>> => {
if (typeof context.params?.id === "string") {
return {
props: {
id: context.params?.id,
},
};
} else {
return {
notFound: true,
};
}
};
const Page = ({ id }: Props) => {
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ?? "";
return (
<>
<Head>
<meta
property="og:image"
key="ogImage"
content={`${baseUrl}/api/ogi?id=${id}`}
/>
<meta
name="twitter:card"
key="twitterCard"
content="summary_large_image"
/>
<meta
name="twitter:image"
key="twitterImage"
content={`${baseUrl}/api/ogi?id=${id}`}
/>
</Head>
<div>
<h1>入力した文字: {id}</h1>
</div>
</>
);
};
export default Page;
// package.json
...
"scripts": {
"dev": "next dev",
"build": "next build",
"now-build": "yum install libuuid-devel libmount-devel && cp /lib64/{libuuid,libmount,libblkid}.so.1 node_modules/canvas/build/Release/ && yarn build",
"start": "next start",
"deploy": "now"
},
...
yarn now-build
instead of yarn build
.