Search code examples
vue.jspaperjs

Using paperjs on a vuejs project based on SFC


I have a vuejs project based on single file components. I want to add a canvas and dinamically draw things with paperjs, based on my component data. What is the proper way to do it?


Solution

  • Self response. A working SFC.

    <template>
        <canvas resize id="main-canvas">{{circle_diameter}}</canvas>
    </template>
    
    <script>
    import paper from 'paper'
    export default {
        data: () => ({ x: 20, y: 20 }),
        props: ['circle_diameter'],
        methods: {
            updateDrawing() {
                paper.setup(document.getElementById('main-canvas'))
                // Now, draw your things based on component state.
                const point = new paper.Point(this.x, this.y)
                const circle = new paper.Path.Circle(point, this.circle_diameter/2)
                circle.fillColor = 'grey'
                circle.strokeColor = 'black'
            },
        },
        updated() {
            this.updateDrawing()
        },
    }
    </script>
    

    EDIT

    Since paperjs will render outside vue scope, drawing is not reactive until you place {{circle_diameter}} into the canvas html tags. This way, you force Vue to call update() each time a prop changes.