如何使用blob和filesaver将Chart JS图表保存为没有黑色背景的图像?

xpcnnkqh  于 2023-01-30  发布在  Chart.js
关注(0)|答案(3)|浏览(204)
  1. $("#NoBidsChart").get(0).toBlob(function(value) {
  2. saveAs(value, "Summary.jpg");
  3. });

这里我使用Chart JS(v2.5.0)来渲染图表。当我尝试使用Canvas to Blob converter和filesaver.js导出图表时,我得到了黑色背景。那么我如何获得具有自定义背景颜色(最好是白色)的图像呢?

ui7jx7zq

ui7jx7zq1#

如果你想要一个自定义的背景颜色,你必须用你喜欢的颜色来画一个背景,你可以这样做,就像这样...

  1. var backgroundColor = 'white';
  2. Chart.plugins.register({
  3. beforeDraw: function(c) {
  4. var ctx = c.chart.ctx;
  5. ctx.fillStyle = backgroundColor;
  6. ctx.fillRect(0, 0, c.chart.width, c.chart.height);
  7. }
  8. });
    • 演示**

x一个一个一个一个x一个一个二个x

mf98qq94

mf98qq942#

正如我在对已接受答案的评论中所述,beforeDraw事件导致fillRect代码被多次调用(就我所见,每个数据点调用一次),这让我很困扰。
但是当在任何其他事件上调用时,我无法让这种方法工作,然而,我只是采用了in this answer描述的编码方法,并将其插入到注册为在afterRender事件上运行的代码中,它就完成了我想要的工作:运行一次,背景为白色。

  1. Chart.plugins.register({
  2. afterRender: function(c) {
  3. console.log("afterRender called");
  4. var ctx = c.chart.ctx;
  5. ctx.save();
  6. // This line is apparently essential to getting the
  7. // fill to go behind the drawn graph, not on top of it.
  8. // Technique is taken from:
  9. // https://stackoverflow.com/a/50126796/165164
  10. ctx.globalCompositeOperation = 'destination-over';
  11. ctx.fillStyle = 'white';
  12. ctx.fillRect(0, 0, c.chart.width, c.chart.height);
  13. ctx.restore();
  14. }
  15. });

请访问linked answer to the other posted question(并投赞成票)。

展开查看全部
iyr7buue

iyr7buue3#

**在React中,使用react-chartjs-2,**我可以设置图表的背景颜色,如下所示:

  1. const plugin = {
  2. beforeDraw: (chartCtx) => {
  3. const ctx = chartCtx.canvas.getContext('2d');
  4. ctx.save();
  5. ctx.globalCompositeOperation = 'destination-over';
  6. ctx.fillStyle = 'white';
  7. ctx.fillRect(0, 0, chartCtx.width, chartCtx.height);
  8. ctx.restore();
  9. }
  10. };

然后将插件添加到图表中:

  1. <Line ref={chartRef} data={chartData} options={options} plugins={[plugin]} />

参考文件

将图表保存为图像:

我创建了一个使用toBase 64 Image函数提取图像的函数。我将此函数附加到一个按钮上,以帮助我在单击按钮时下载图表图像。

  1. function downloadImage(){
  2. const link = document.createElement("a");
  3. link.download = `${chart.name || 'chart'}.jpg`
  4. link.href = chartRef.current.toBase64Image('image/jpeg', 1);
  5. link.click();
  6. }
展开查看全部

相关问题