在 canvas 和 charts.js 旁边显示 base64 图像

Show base64 image next to canvas with charts.js

我正在使用 charts.js,它可以选择添加包含 canvas 的 base64 图像的属性,如下所示:

animation: {
    onComplete: function(animation){
        document.querySelector('#myChart').setAttribute('href', this.toBase64Image());
    }
},

这是完整的工作 fiddle:https://jsfiddle.net/0on3f7t7/

当您检查 canvas 时,您可以看到包含图像的 href 属性,这样就可以了。但是我需要在 canvas 下方显示图像。所以,是的,屏幕上会有两个图表,canvas 版本和图像版本。

无论如何我都找不到这个问题的答案,文档也没有给出任何线索。

您需要在页面中添加一个<img>元素,然后将<img>元素的src属性设置为this.toBase64Image()[=16的输出=]

见下文fiddle:

https://jsfiddle.net/wveepa7c/

onComplete: function(animation){
  // #myImage is an img element
  document.querySelector('#myImage').setAttribute('src', this.toBase64Image());
}

onComplete 在 jsfiddle 中至少被调用了两次。你可以定义一个变量undefined,在onComplete处检查是否定义了变量,以防止<img>被附加到document两次,如果没有定义变量,则创建<img> 元素,使用 .insertAdjacentHTML() 链接到 ctx,第一个参数 "afterend" 和第二个参数 .outerHTML of <img> element

var img;

animation: {
  onComplete: function(animation) {
    if (!img) {
      ctx.setAttribute('href', this.toBase64Image());
      img = new Image;
      img.src = ctx.getAttribute('href');
      ctx.insertAdjacentHTML("afterend", img.outerHTML)
    }
  }
}  

https://jsfiddle.net/0on3f7t7/2/