Importing CanvasJS



  • I want to use the CanvasJS library in the quasar framework and have had no luck getting it to work. I have tried importing it directly into the component, and in a plugin with no success. Has anyone else been able to get it functional? I am using the canvas.min.js file.



  • Working with libraries in Quasar is just like working with them in Vue. Have you tried installing via canvasjs vie NPM (or Yarn) and then using a plugin along the lines of:

    // src/plugins/canvas.js (or whatever and don't forget to add it to quasar.conf.js)
    const CanvasJS = require('../../node_modules/canvasjs/dist/canvasjs.min.js')
    
    export default ({ Vue }) => {
      Vue.prototype.$canvas = CanvasJS
    }
    

    …and then in any Vue component it’s this.$canvas:

    <!-- src/pages/Canvas.vue -->
    <template lang="html">
      <div id="chartContainer" style="height: 360px; width: 100%;"></div>
    </template>
    
    <script>
    export default {
      data () {
        return {
          chartOptions: {
            title: {
              text: 'CanvasJS Chart in Quasar'
            },
            data: [
              {
                type: 'column',
                dataPoints: [
                  { x: 10, y: 71 },
                  { x: 20, y: 55 },
                  { x: 30, y: 50 },
                  { x: 40, y: 65 },
                  { x: 50, y: 95 },
                  { x: 60, y: 68 },
                  { x: 70, y: 28 },
                  { x: 80, y: 34 },
                  { x: 90, y: 14 }
                ]
              }
            ]
          },
          chart: null
        }
      },
      mounted () {
        this.chart = new this.$canvas.Chart('chartContainer', this.chartOptions)
        this.chart.render()
      }
    }
    </script>
    

    Add a route for it and go to that page and you should see the chart in all it’s glory. And this is about the 10th time I have shown how to add JS libraries to Vue/Quasar on this forum, so hopefully folks will start searching first 😉

    0_1536327796596_d70e8379-849b-4c7b-b421-23ccfd75bac8-image.png