【问题标题】:Adding image on chart js在图表js上添加图像
【发布时间】:2021-07-15 11:08:13
【问题描述】:

我有一个使用 Chart.js 3.4.1 创建的图表 如何在图表的右下角添加图像

chart

【问题讨论】:

  • 请分享一些关于您遇到问题的具体问题。 stackoverflow 是针对特定问题的,而不是针对教程请求的。
  • 抱歉,问题是我尝试了多种方法,但它们要么根本不起作用,要么看起来不太好,这就是为什么我问了一个一般问题,因为我很好奇正确的做法感谢您的反馈下次我会考虑它

标签: javascript image canvas chart.js


【解决方案1】:

您可以使用自定义插件使用drawImage() 方法在画布上绘制图像:

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

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: "pink"
    }]
  },
  options: {},
  plugins: [{
    id: 'customImage',
    beforeDraw: (chart) => {
      if (image.complete) {
        const ctx = chart.ctx;
        const {
          top,
          left,
          width,
          height
        } = chart.chartArea;
        const x = left + width - image.width;
        const y = top + height - image.height;
        ctx.drawImage(image, x, y);
      } else {
        image.onload = () => chart.draw();
      }
    }

  }]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

【讨论】:

    【解决方案2】:

    以下是基于 CSS 的解决方案。请参考我刚刚创建的这个示例并根据需要编辑 CSS>>https://jsfiddle.net/0paz7Lqr/1/

    HTML:

     <canvas id="chart" width="390" height="225"></canvas>
    

    JS:

        var barData = {
        labels: ["John W", "Ben T", "Jenny H", "Samantha D", "Anothony P"],
        datasets: [
            {
                fillColor: "rgba(153, 153, 155, 0.4)",
                highlightFill: "#7C7C7C",
                strokeColor: "#7C7C7C",
                pointColor: "#7C7C7C",
                pointStrokeColor: "#7C7C7C",
                pointHighlightFill: "#fff",
                data: [25, 94, 68, 175, 66]
            }
        ]
    };
    
    var ctx = $("#chart").get(0).getContext("2d");
    var myChart = new Chart(ctx).Line(barData);
        
    

    CSS:

     canvas {
       background-image: url(https://homepages.cae.wisc.edu/~ece533/images/airplane.png);  
       background-size: 35% 25%;
       background-position: bottom 30px right 20px;  
       background-repeat: no-repeat;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2014-04-17
      • 1970-01-01
      相关资源
      最近更新 更多