nuxtjsにfabricjsを導入するときの情報が少なかったのでそのメモです。
必要な項目のインストール
yarn add fabric
yarn add canvas
package.jsonとyarn.lockに追加される。
plugin直下にfabric.jsファイルを作成。
fabric.js
import { fabric } from 'fabric'
import Vue from 'vue'
Vue.use(fabric)
export default fabric
nuxt.config.jsに情報を追加
nuxt.config.js
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{
src: '@/plugins/fabric',
mode: 'client'
}
],
実際のコード
これは赤い四角形を表示するためのサンプル
fabric/index.vue
<template>
<canvas ref="can" width="200" height="200"></canvas>
</template>
<script>
import { fabric } from 'fabric';
export default {
mounted() {
const ref = this.$refs.can;
const canvas = new fabric.Canvas(ref);
const rect = new fabric.Rect({
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
}
};
</script>
これで localhost:3000/fabricにアクセスすると以下のように赤い四角形が表示されているはず。
参考
