在隐藏的DIV上渲染Chartjs [英] Render Chartjs on hidden DIV

查看:86
本文介绍了在隐藏的DIV上渲染Chartjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在隐藏的div上使用 chart.js 渲染许多图表,然后将其转换图片以用于PDF报告中.

I'm trying to render many charts using chart.js on a hidden div, then convert them to images to use in a PDF report.

我的问题是:如果图表未在DOM上呈现,我将无法捕获它并在 canvas 上绘制它.在显示图表之前,它不会呈现.我尝试使用 chart.js 中的 draw render 方法,但是它们无法产生预期的结果.

My problem is: if the chart is not rendered on the DOM, I can't capture it and draw it on a canvas. Until the chart is shown, it doesn't render. I've tried to use the methods of draw and render from chart.js but they don't produce the desired results.

这是我的示例HTML:

Here's my example HTML:

<div style="display: none;">
  <canvas id="myChart"></canvas>
</div>

和我相应的JavaScript:

And my corresponding JavaScript:

var canvas: any = document.getElementById('myChart');
var ctx: any = canvas.getContext('2d');
var chart = new Chart(ctx, {
    // The type of chart we want to create
    type: 'line',
    // The data for our dataset
    data: {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
          }]
        },

        // Configuration options go here
        options: {}
      });

for (var id in Chart.instances) {
    Chart.instances[id].resize();
    Chart.instances[id].draw('1s');
    Chart.instances[id].render('1s');
    console.log(Chart.instances[id].toBase64Image());
}

有什么方法可以手动呈现图表而不显示它,然后将输出捕获为图像?

Is there any way to manually render the chart without displaying it, then capture the output as an image?

推荐答案

最快的破解方法是替换:

The fastest hack would be to replace:

<div style="display: none;">

使用

<div style="position:absolute;left:-9999px;top:-9999p">

,它将起作用: https://jsfiddle.net/FGRibreau/n1cx9d70/2/:)

PS:如果需要在服务器端呈现图表(例如,以批处理的形式),然后将其嵌入PDF报表中,则您可能需要考虑使用诸如

PS: If you need to render the chart server-side (e.g. in a batch) in order to then embed it inside PDF reports then you might want to consider dedicated services like Image-Charts.

这篇关于在隐藏的DIV上渲染Chartjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆