W
W
weraleto2020-02-02 14:57:24
Canvas
weraleto, 2020-02-02 14:57:24

How to draw canvas vue.js line?

I'm trying to write a simple code, where one of the components has a built-in canvas on which you can draw with the mouse . I sketched a simple code that works without using
vue.js the component reacts to the event, but the line does not build , what could be the reason? component code below


<template>
    <div class="app-wrapper" >
        <canvas id="canvas"
            @mouseup="finishedPosition()"
            @mousedown="startPosition()"
            @mousemove="draw($event)"
        ></canvas>
    </div>
</template>

<script>
export default {
    data() {
        return {
            painting:false
        }
    },
    methods: {
        startPosition(){
            this.painting=true;
        },
        finishedPosition(){
            this.painting=false;
            this.ctx.beginPath();
        },
        draw(event){
            if(this.painting){
                canvas.height=288;
                canvas.width=document.querySelector('.app-wrapper').clientWidth;
                this.ctx.lineWidth=5;
                this.ctx.lineCap='round';

                this.ctx.lineTo(event.clientX, event.clientY);
                this.ctx.stroke();
                this.ctx.beginPath();
                this.ctx.moveTo(event.clientX, event.clientY);
                this.ctx.fill()
            }
        }
    },
    computed: {
        ctx(){
            return document.querySelector('#canvas').getContext('2d');
        }
    },

}

</script>

<style scoped>
    .app-wrapper {
        min-height: 288px;
        max-width: 82.92%;
    }
</style>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-02-02
@weraleto

https://jsfiddle.net/95fjzq2g/

A
Andrey Suha, 2020-02-02
@andreysuha

Try accessing canvas via refs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question