设置背景颜色以保存画布图表

Bru*_*uno 6 javascript canvas typescript chart.js

我使用 ChartJS 并将它们保存在本地,将画布上的图表图像转换为数据 blob,然后保存。但是我无法设置我保存的任何画布图表的背景颜色,我只能保存没有背景颜色的图表,这让用户感到困惑。

到目前为止我尝试过的是:

  1. 将 image/png 的类型更改为 image/jpg
  2. 创建一个带有样式的文档,并将其作为子项附加到我的 document.createElement 中,该文档将包含图像
  3. 为我的“链接”赋予样式,该样式与上面的 document.createElement 相同

但没有成功,图像是在没有背景的情况下正确下载的。

我在搜索并找到了一些主题:

创建一个带有背景图像的画布并保存

用背景图像保存画布

但是,在所有工作结束时,无法为我找到解决方案。

我的 html 图表是:

<canvas id="divName"></canvas>
Run Code Online (Sandbox Code Playgroud)

用于保存图像的打字稿函数,使用 bytearray 创建一个新的 blob,图像的类型是:(该代码已尝试添加背景颜色)

saveimg(divName){
      let canvas:any;

        let style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = '.cssClass { background-color: "aquamarine"; }';

        if(this.deviceValue != null) {
          canvas = document.getElementById(this.deviceValue);
      }
      else {
          canvas = document.getElementById(divName);
      }

//SOLUTION that works BY Caleb Miller ***********
fillCanvasBackground(canvas, 'white');

function fillCanvasBackground(canvasc, color)
{
   const context = canvasc.getContext('2d');
   context.save();
   context.globalCompositeOperation = 'destination-over';
   context.fillStyle = color;
   context.fillRect(0, 0, canvasc.width, canvasc.height);
   context.restore();
}
// end***********************

        let dataURL = canvas.toDataURL();
        let datablob = dataURL.substring(dataURL.indexOf(",") + 1);

     let byteCharacters = atob(datablob);
     let byteNumbers = new Array(byteCharacters.length);
     for (let i = 0; i < byteCharacters.length; i++) {
         byteNumbers[i] = byteCharacters.charCodeAt(i);
     }

     let byteArray = new Uint8Array(byteNumbers);
     let blob = new Blob([byteArray], {"type": "image/jpg"});


     if(navigator.msSaveBlob){
         let filename = this.chartTitle + ' - ' + this.entityName;
         navigator.msSaveBlob(blob, filename);
     } else {
         let filename =this.chartTitle + ' - ' + this.entityName;
         let link = document.createElement("a");

         link.onload = function() {
             canvas.drawImage(0,0);
         };

         document.getElementsByTagName('a')[0].appendChild(style);
         link.href = URL.createObjectURL(blob);
         link.setAttribute('visibility','hidden');
         link.download = filename;
         link.style.backgroundColor = "lightblue repeat-x center";

         document.body.appendChild(link).style.background = "lightblue repeat-x center";
         link.click();
         document.body.removeChild(link);
     }
        this.deviceValue = null;
    }
Run Code Online (Sandbox Code Playgroud)

表达问题的图片:

在网站上的图像是:

当我下载它时

是否可以为画布图像添加背景颜色?

Cal*_*ler 13

正如你发现的那样, canvas.toDataURL()不会捕获通过 CSS 应用的任何视觉样式。它只从支持画布实例的位图中捕获原始像素数据。这是设计使然。

为了使用自定义背景颜色,您需要将其直接绘制到画布上。这是一个用给定颜色填充给定画布背景的函数示例。我的内嵌评论应该解释它是如何工作的。

function fillCanvasBackgroundWithColor(canvas, color) {
  // Get the 2D drawing context from the provided canvas.
  const context = canvas.getContext('2d');

  // We're going to modify the context state, so it's
  // good practice to save the current state first.
  context.save();

  // Normally when you draw on a canvas, the new drawing
  // covers up any previous drawing it overlaps. This is
  // because the default `globalCompositeOperation` is
  // 'source-over'. By changing this to 'destination-over',
  // our new drawing goes behind the existing drawing. This
  // is desirable so we can fill the background, while leaving
  // the chart and any other existing drawing intact.
  // Learn more about `globalCompositeOperation` here:
  // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  context.globalCompositeOperation = 'destination-over';

  // Fill in the background. We do this by drawing a rectangle
  // filling the entire canvas, using the provided color.
  context.fillStyle = color;
  context.fillRect(0, 0, canvas.width, canvas.height);

  // Restore the original context state from `context.save()`
  context.restore();
}
Run Code Online (Sandbox Code Playgroud)

要使用该函数,请在保存代码之前调用它,并为其提供图表画布和颜色。它应该是这样的:

const canvas = document.getElementById('yourCanvasId');
fillCanvasBackgroundWithColor(canvas, 'aquamarine');
// ...the rest of your save code
Run Code Online (Sandbox Code Playgroud)

保存的图像应具有背景颜色。

  • 我只是拿了这段代码,把它放在一个注册到 afterRender 事件的插件中。它是一种享受。请参阅我的组合解决方案:/sf/answers/3776266231/ 谢谢。 (2认同)