Skip to content

ブラウザで描画する ​

以下のコマンドで Vite プロジェクトを作成します。既存の ESM フロントエンドでは yugioh-card をインストールし、ページ上のコンテナー要素を使えます。

bash
npm create vite@latest card-preview -- --template vanilla
cd card-preview
npm install
npm install yugioh-card

静的リソースに沿って public/card-assets を用意します。テンプレートの #app を残し、エントリーファイルを次のコードに置き換え、npm run dev を実行します。

js
import { YugiohCard } from 'yugioh-card';

const app = document.querySelector('#app');
const view = document.createElement('div');
const save = document.createElement('button');
const status = document.createElement('p');

save.type = 'button';
save.textContent = 'Download PNG';
save.disabled = true;
status.setAttribute('role', 'status');
app.replaceChildren(view, save, status);

const card = new YugiohCard({
  view,
  resourcePath: `${import.meta.env.BASE_URL}card-assets`,
  data: {
    language: 'en',
    name: 'Demo Dragon',
    attribute: 'light',
    level: 8,
    monsterTypeLine: 'Dragon / Normal',
    cardText: 'A dragon drawn on Canvas.',
    atk: 3000,
    def: 2500,
    renderScale: 0.4,
  },
});

try {
  await card.ready;
  save.disabled = false;
} catch (error) {
  status.textContent = error.message;
}

save.addEventListener('click', async () => {
  save.disabled = true;
  status.textContent = '';
  try {
    await card.ready;
    await card.leafer.export('card.png', { screenshot: true, pixelRatio: window.devicePixelRatio });
  } catch (error) {
    status.textContent = error.message;
  } finally {
    save.disabled = false;
  }
});

イラストを表示するには、公開ディレクトリに画像を置き、その URL を data.artwork に指定します。card.setData({ name: 'Another Dragon' }) でカード名を更新できます。更新後は card.ready を取得し直し、描画が完了してから書き出してください。

renderScale は描画サイズを指定します。画面上のプレビューだけを拡大・縮小する場合は、外側のコンテナーを縮尺します。コンポーネントのアンマウント時は card.leafer.destroy(true) を呼び出します。各カードのフィールドは API リファレンスを参照してください。

オプションの詳細は Leafer での書き出しと破棄を参照してください。