Reputation: 1209
I've got a component with two vue-tab
s, with two instances of vue-chart-js
in each of it. Though they get initialized without errors, a chart in the unactive tab returns nothing, when I try to extract an image from it via document.querySelector('#mySecondChart').toDataURL()
. Only when I click that tab and make it active, this chart transforms into image. The chart in the default active tab transforms into image without errors. Here's the code:
<template>
<div>
<vue-tabs>
<v-tab>
<my-first-chart-component/>
</v-tab>
<v-tab>
<my-second-chart-component/>
</v-tab>
</vue-tabs>
<button @click="extractCharts">Extract charts</button>
</div>
</template>
<script>
// imports omitted
export default {
name: 'MyParentComponent',
// data and props omitted
methods: {
extractCharts() {
let charts = document.querySelectorAll('chart')
let firstChart = charts[0].toDataURL();
let secondChart = charts[1].toDataURL();
console.log(`${firstChart} \n\n\n ${secondChart}`)
}
}
}
</script>
When I click the button without going to second tab, my method outputs the DOMString of the first chart and nothing of the second chart. Only when I visit the second tab first, and then click the button, my method returns both stringified charts. Is there any way to forcefully get second chart rendered without even activating the tab containing it?
Upvotes: 0
Views: 1924
Reputation: 11
This worked for me. Put the code inside mounted hook.
var canvas = document.getElementById('line-chart');
canvas.removeAttribute('width');
canvas.removeAttribute('height');
canvas.setAttribute('style', 'display: block; width: 100% !important; height: auto !important;');
Upvotes: 1
Reputation: 1209
After searching through documentation, I've discovered that the reason of the problem lies within Chart.js itself -- if the parent element containing the chart has display: none
or is hidden in some other ways, the canvas rendered in it gets the height and width properties equal to 0. This may be avoided if during chart instance's initialization pass to its options the following parameters:
options: {
// other options
responsive: false,
maintainAspectRatio: true
}
Then the canvas element bound to the chart instance would keep width and height properties passed to it in markup (i.e. <canvas id="myChart" width="1137" height: "447"></canvas>
) and it's display
property will remain with the value of block
even if the parent element is hidden.
Upvotes: 3