Struggling to get my chart to render dynamically in vue-chartjs

In my MainChart.vue file, I defined my chart like this:

import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins
// const brandPrimary = '#20a8d8'
export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options', 'chartData', 'height'],
  mounted () {
    this.renderChart(this.chartData, this.options)
    var elements = 1
  }
}

I ran a test on this code and it worked perfectly.

<line-chart :chartData="myChartData"></line-chart>

However, when I attempted to render the chart dynamically, it didn't work.

import lineChart from './MainChart';

// ...

let chartClass = Vue.extend(lineChart)
let chartInstance = new chartClass({
  propsData: {
    chartData: myChartData
  }
})
chartInstance.$mount()
console.log(chartInstance.$el)
console.log(chartInstance.$el.querySelector("canvas").toDataURL('image/png'))
console.log(chartInstance.$refs.canvas)
console.log(chartInstance.$refs.canvas.toDataURL('image/png'))

When checking the console messages, I noticed that nothing was being drawn in the canvas area.

How can I go about rendering my chart dynamically?

For more information, please refer to these related questions:

  • Is it possible to print a chart with vue-chartjs?

Answer №1

If you are looking to retrieve complete image data, it is essential to wait until the chart rendering process is completed. Utilizing a 'Promise' can be quite beneficial in this scenario.

 async function generateChart(data, index, width, height) {
  var canvas = document.createElement("canvas");
  canvas.width = 765;
  canvas.height = 382;
  //canvas.style.width = "765px";
  //canvas.style.height = "382px";
  //canvas.style.display = "none";
  canvas.id = "dynamicChart";
  document.body.appendChild(canvas);

  var ctx = document.getElementById("dynamicChart").getContext('2d');
  var draw = () => new Promise((resolve, reject) => {
   new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
     responsive: false
    }
   })
   setTimeout(() => resolve(), 100);
  });

  await draw();

  let imageData = document.getElementById("dynamicChart").toDataURL("image/png");
  console.log(imageData);

  addImage(imageData, index, width, height);
  document.body.removeChild(canvas);
 }

 // ...

 await generateChart(myChartData, 0, 400, 300);

If you need to plot multiple charts within a loop, consider using this approach:

let chartFunctions = [];
myList.forEach((item) => {
  chartFunctions.push(async function() {
    await generateChart(myChartData, 3, 160, 80);
  });
}

for(let k in chartFunctions) {
  await chartFunctions[k]();
}

Check out these console messages for more details:

https://i.sstatic.net/l93xc.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

experimenting with encoding an image in base64 and implementing it

After coming across a block of code online, I've encountered a situation where it seems to be functioning and malfunctioning simultaneously. It's quite possible that my lack of comprehension is the root cause, as I'm struggling to make it wo ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

What is the best way to delete the "Click to sort Ascending" text from the header of each column in a bootstrap-vue table?

Recently, I came across a bootstrap-vue table that caught my attention: Below is the code snippet for the table setup: <template> <div class="container"> <h1 class="pt-2 pb-3">Bootstrap Table</h1> ...

Generating and Retrieving Dynamic URL with Jquery

My web page named single-colur.html has the ability to handle various query strings, such as: single-colour.html?id=1 single-colour.html?id=2 single-colour.html?id=3 single-colour.html?id=4 The parameter id in the URL corresponds to an entry in a table c ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

Animate the div only when the button is clicked

I need a way to hide the text inside a div when it exceeds a certain height, but then expand it to full height upon clicking a button. However, I want this action to only affect the parent div of that specific button, rather than all the divs on the page. ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

Javascript window.scroll function malfunctioning in some browsers while running in localhost

Check out this codepen link where everything is working, but unfortunately not locally: https://codepen.io/LoudDesignStudios/pen/RwxPJKY <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> < ...

Search for all documents in MongoDB and update all of them except for one

After performing a database lookup, I am receiving an array of objects as a result. [ { name: "test", services: { credentials: "123456" } }, { name: "test1", services: { credentials: "1 ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

chaotic telerik editor arrangement

I have incorporated the Rad Editor into my ASP.NET page. <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <telerik:RadEditor ID="reSummery" runat="server" > </telerik:RadEditor> Despite not referencing ...

I am unfamiliar with this specific JavaScript algorithm problem from Codewars

I need help with a JavaScript algorithm question This problem involves extracting two letters from the middle of odd-numbered characters My confusion lies in function getMiddle(s) { //Code goes here! let answer = ""; if (s.length % 2 !== 0) { a ...

A small computation

How can I modify this code to calculate the total price #ttc by multiplying #totalcout with #marge Currently, I am able to add amounts when checkboxes are clicked, but I am struggling with integrating the multiplication for calculating the Total Price (TT ...

Tips for extracting data from a PHP loop and displaying it in a div element

When I click on a PHP while loop, I want to change the value of a div. Here is my PHP code: <?php $query = mysql_query("select * from tbl_sub_product where product_id='$id'"); while($row=mysql_fetch_array($query)) { ?> <div>< ...

Utilizing CSS for styling a class with a dynamic name

On the server side, I am dynamically generating class names like this: <p class="level_1">List item 1</p> <p class="level_2">List item 2</p> <p class="level_3">List item 3</p> <p class="level_1">List item 1</p& ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

Passing parameters to Next.js pages

Here is my function: export async function getServerSideProps({ req }: any) { const user = ( await axios.get("http://localhost:4000/api/auth/status", { withCredentials: true, headers: { Cookie: `connect.sid=${req.cookies["c ...

Is there a way to transition an element from a fixed layout position to an absolute layout position through animation?

I am looking to create a dynamic animation effect for a button within a form. The goal is for the button to move to the center of the form, while simultaneously undergoing a horizontal flip using a scale transform. During the midpoint of this animation, I ...

Troubleshooting Problem with ListItem Alignment in Material UI v0 involving Custom Avatar Component

Material UI version: v0.20.0 I'm facing an issue with aligning the leftAvatar value using the CustomAvatar component, as shown in the attached screenshot. Any assistance would be appreciated. CustomAvatar: The functionality of this component is cond ...

Automated tools and frameworks for the testing of website performance

Hello, I have a website that heavily relies on AJAX for server communication. I am looking to conduct performance and stress testing using automated scripts. Can you provide any suggestions or recommendations? I am specifically interested in the functiona ...