可以在ChartJS中使用图像作为条形图的背景色吗?

wb1gzix0  于 5个月前  发布在  Chart.js
关注(0)|答案(1)|浏览(58)

我想创建一个条形图,其中一个条形图中有一个图像,它看起来像图像显示的酒吧动画进入视图。
我尝试创建一个保存图像的变量,并将该栏的backgroundColor设置为该变量。

var img = new Image();
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
    };
    img.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';

字符串
在chart config中:

backgroundColor: [
          'rgba(255, 255, 255, 0)',
          img,
          'rgba(255, 255, 255, 0)'
          ],


这只会导致一个黑色的条。我有点想这样做:Fill Chart.js bar chart with diagonal stripes or other patterns只与一个预定义的jpg。

gkl3eglg

gkl3eglg1#

感谢@kikon修复了我的代码后,下面的代码应该可以回答你的问题。你可以在这里找到文档。

const ctx = document.getElementById('myChart').getContext('2d');

const image = new Image();
image.src = 'https://www.chartjs.org/img/chartjs-logo.svg';

image.onload = function(){
  const fillPattern = ctx.createPattern(image, 'repeat');

  const cfg= {
    type:'bar',
    data:{
      labels:[0,1,2,3],
      datasets:[{
        label: 'A',
        backgroundColor:['black', 'red', 'blue', fillPattern],
        data: [2,4,6,8]
      }]
    }
  }

  const myChart = new Chart(ctx, cfg);
}

个字符

相关问题