设置背景颜色以保存画布图 [英] set background color to save canvas chart

查看:145
本文介绍了设置背景颜色以保存画布图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im using ChartJS and saving them locally, converting the chart image on canvas to data blob and then save it. But I'm having trouble setting background color of whatever canvas chart im saving, i can only save the chart without background color, confusing the user.

我尝试了什么到目前为止是:

What I've tried so far was:


  1. 将图片类型/ png更改为图片/ jpg

  2. 创建一个带有样式的文档,并将其作为子项附加到我的
    document.createElement,它将具有图像

  3. 为我的链接提供与文档相同的样式.createElement
    以上

但没有成功,图像可以在没有背景的情况下下载。

But no success, the image is corrctely downloaded without background.

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

i was searching and found some topic:

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

使用高建群保存画布ound image

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

but, at the end of all the work, wasn't abble to find the solution for me.

我在html上的图表是:

My chart on html is:

<canvas id="divName"></canvas>

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

the typescript function to save the image, creating a new blob with bytearray and the type of the image is: (that code has all the tries to add background color)

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;
    }

表达问题的图片:

网站上的图片是:

我下载时

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

is it possible to add background color to a canvas image?

推荐答案

如您所见, canvas.toDataURL()未捕获任何通过CSS应用的视觉样式。它仅捕获支持画布实例的位图中的原始像素数据。这是设计使然。

As you discovered, canvas.toDataURL() does not capture any visual styling applied via CSS. It only captures the raw pixel data from the bitmap backing the canvas instance. This is by design.

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

In order to use a custom background color, you need to draw it directly to the canvas. Here is an example of a function that fills the background of a given canvas with a given color. My inline comments should explain how it works.

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();
}

要使用此功能,请在保存代码前调用它,并将其设为图表帆布和颜色。它看起来应该是这样的:

To use the function, call it before your save code, giving it the chart canvas and a color. It should look something like this:

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

保存的图片应该有一个背景颜色。

The saved image should have a background color.

这篇关于设置背景颜色以保存画布图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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