VueJS + PaperJS: A Canvas Story
First things first, let’s install the VueJS CLI to create our app.
npm install -g @vue/climkdir vuecd vuevue create vue-canvas
This will create a boilerplate app generated by Vue’s CLI. It may take a bit, choose all defaults. Now, let’s kick off our UI for the first time.
cd vue-canvasnpm run serve
If you’re not familiar with VueJS, I recommend reading the getting started documentation on the website (Link is at the top of the article). I will use many of the concepts, but not dive deeply into any explanation of the infrastructure of VueJS.
Since I’m not a big fan of writing CSS code, for this tutorial I am going to be using Bootstrap in my project, for a 1-minute install tutorial I suggest you follow this link: bootstrap set-up.
To set-up a clean directory structure, remove the HelloWorld.vue component generated by Vue and create a new directory called pages. Create two new components: pages => Master.vue and components => Canvas.vue.
Now, Let’s code.
The App.vue file will simply import our master component that will wrap the canvas and provide some base styling for our application.
The Master.vue file will wrap the canvas component to provide a layout. We will also create a clear button to reset our canvas, but all the logic for that will be stored in the child component. To reference that function from the parent we can easily do that using VueJS refs.
Lastly, we will create our Canvas.vue component that will be a single, draw-able canvas, that extends the functionality from PaperJS.
npm install --save paper
Attaching our PaperJS scope to the canvas:
this.scope.setup(this.canvasId);
Creating our path:
return new paper.Path({
strokeColor: "#000000",
strokeJoin: 'round',
strokeWidth: 1.5
})
Creating our tool:
return new paper.Tool();
On mouse down, we are using the PaperJS Tool to draw, and it knows where and what to draw because we have attached our path and setup our canvas scope.
PaperJS is a powerful JS package we can use to extend the functionality of our web applications. Enjoy! :). Github Repo.