How to use SVG.js with Vue.js

Hoch Ohmig
1 min readFeb 27, 2021

I am going to write a quick article on how to use SVG.js library in Vue.js project. As a beginner in the framework, I spent a lot of time trying to find how to exactly to do it. So I am putting this down here, so you don't waste your time trying to figure out how to do something so fundamental like I did.

First Step is to install Svg.js to your vue project. You can do this by running

npm install @svgdotjs/svg.js

After it is installed you want to make a SVG.js plugin for your project. To do this, simply make a folder inside src directory, create a file called vueSvgPlugin.js . The content of the file should be as follows:

import svgJs from “svg.js/dist/svg”export default {install: Vue => {Vue.prototype.$svg = svgJs}}

In your main.js file, add the following

import svgJs from "./plugins/vueSvgPlugin";Vue.config.productionTip = falseVue.use(svgJs);

Now you can acess svgJS using this.svg from anywhere inside your Vue project. For the sake of completeness, here is an example to draw a simple rectangle inside a .vue file using SVG.js

<template><div><h1> Example </h1><div :id="svgId" class="svg-container"></div></div></template><script>
export default {
name: "example",
data: () => ({
svgId : "thisID",
svgContainer: null,
},
methods: {
generateRect: function() {
const svgContainer = this.$svg("example").size(100,100);const rectangle = svgContainer.rect(100,100).attr({ fill: '#f06' });this.svgContainer = rectangle},
mounted() {
this.generateRect()
}
<style></style>

This concludes it.

--

--