![見出し画像](https://assets.st-note.com/production/uploads/images/141800074/rectangle_large_type_2_33dba73c7b374b9a0a8213c17a2876af.png?width=1200)
Obsidian で簡易的な OGP を作る Templater スクリプトを作ってみた
note を始めて一ヶ月が経ち、そろそろ OGP でも作るか~と言って Excalidraw プラグインを入れてみましたがオーバースペックだったので、サクッと簡易的な OGP を作れる Templater スクリプトを作りました。
ヘッダーのような画像が作れます。
必要なもの
Templater プラグイン
Dataview プラグイン
どんな感じに作用するのか
プロパティで「OGP」を指定し、出力したいタイトルを入力します。タイトルの折り返しは「|」です。折り返したいところに入れてください。
例
OGP:: ここに|タイトルを|入力
DataviewAPIを使っているので、文章に「OGP::(ここにタイトルを入力)」と書いてしまっても機能します。僕はこっちのほうが好み。
OGPを書いたら、スクリプトを起動します。
1920 × 1080 の OGP 画像ができます(ダウンロードウィンドウが開くので適宜保管してください)。
楽しい!
コード
以下のファイルを保存して、Templater プラグインに登録してください。
<%*
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const dv = app.plugins.plugins.dataview.api;
OGPtitle = dv.page(tp.file.path(true)).OGP;
canvas.width = 1920; // キャンバスの幅
canvas.height = 1080; // キャンバスの高さ
// 背景を白に設定
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// テキストを描画
ctx.fillStyle = 'black';
ctx.font = '120px serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const text = OGPtitle
const maxWidth = 300; // テキストの最大幅
const lineHeight = 150; // 行間
function wrapText(context, text, x, y, maxWidth, lineHeight) {
const words = text.split('|');
let line = '';
const lines = [];
for (let n = 0; n < words.length; n++) {
const testLine = line + words[n] + '|';
const metrics = context.measureText(testLine);
const testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
lines.push(line);
line = words[n];
} else {
line = testLine.replace('|','');
}
}
lines.push(line);
for (let k = 0; k < lines.length; k++) {
context.fillText(lines[k], x, y + k * lineHeight);
}
}
// テキストをキャンバスの中央に折り返して描画
const x = canvas.width / 2;
const y = canvas.height / 1.75 - (lineHeight * (text.split('|').length / 2));
wrapText(ctx, text, x, y, maxWidth, lineHeight);
// キャンバスを画像として保存
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'canvas_image.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}, 'image/png');
%>
参考リンク
まとめ
クソ簡易的ですが、そこそこ使えますね。