LoginSignup
22
16

More than 3 years have passed since last update.

canvasとvuejsの連携を初心者なりに調べた

Last updated at Posted at 2019-06-30

ちょっとjavascriptを使って、canvasとvuejsの連携を試す必要性が出てきたものの、調べるのに時間がかかったのでここにメモを。

方針

  • vuejsで変化した値に応じて、canvasの描画を変えたい
  • なるべくシンプルなコードで
    • コンポーネントについて、自分が理解しきれていない

参考にさせて頂いたもの

実際の中身

index.js
let app = new Vue({
    data(){
        // 値を関数で宣言する
        // 関数で宣言しておくのが標準らしい
        return{
        canvas: null,
        context: null,
        px : 20
        }
    },
    mounted(){
        // 読み込まれる際の定義
        // refによってdiv内の要素を指定する
        this.canvas = this.$refs.canvas;
        this.context = this.canvas.getContext("2d");
        this.draw(this.px);
    },
    watch:{
        //pxの値が変わり次第、this.drawする
        px : function(val,oldVal) {
            this.draw(val);
            console.log('new: %n, old: %o', val, oldVal);
        }
    },
    methods:{
        draw(px){
            let ctx = this.context.canvas.getContext("2d");
            // 引数のpxをlinewidthに
            ctx.lineWidth = px;
            // 1度消す
            ctx.clearRect(0, 0, 400, 400)
            // 以下で壁を作成
            ctx.strokeRect(75, 140, 150, 110);
            // 以下でドアを作成
            ctx.fillRect(130, 190, 40, 60);
            // 以下で屋根を作成
            ctx.moveTo(50, 140);
            ctx.lineTo(150, 60);
            ctx.lineTo(250, 140);
            ctx.closePath();
            // この設定で描画
            ctx.stroke();
        }
    }
}).$mount('#a01')
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="a01">
    <h2>{{px}}px</h2>
    <p><input v-model.number="px"></p>
    <canvas id="canvas" ref="canvas" width="400" height="400"></canvas>
    <br>
</div>
<script src="index.js"></script>
</body>

分からなかったので調べて理解した箇所

ref

  • htmlの要素自体を取得する。
  • つまり今回なら、div内のcanvasを呼び出すために必要

console.logの%oとか

console.log('new: %n, old: %o', val, oldVal);

このあたりを見ると良さそう。

https://qiita.com/nakajmg/items/0a27c6642268243c8eef

new Vueのmountedなど

  1. data
    • 「関数にしておくこと」byアドバイスくれた方
  2. mounted
    • 読み込まれる際にする処理
    • ここではデフォルト値で初回の描画を行う
  3. watch
    • 変数pxについて監視し、変化があれば実行される
  4. methods
    • Vue インスタンスに組み込まれるメソッドです
    • 追加の関数定義を行う場所?あとで勉強しておく
22
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
16