2017-04-23 61 views
0

我使用它有一個選項charts.js添加包含畫布的一個base64圖像的屬性,就像這樣:顯示下與charts.js以帆布的base64圖像

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

下面是完整的工作小提琴:https://jsfiddle.net/0on3f7t7/

當你檢查畫布,你可以看到一個包含圖像的href屬性,這樣的作品。但是,我需要在畫布下方顯示圖像。所以,是的,屏幕上會有兩個圖表,畫布版本和圖像版本。

無論如何,我找不到這個問題的答案,並且文檔沒有給出任何線索。

回答

1

你需要一個<img>元素添加到您的網頁,然後<img>元素的src屬性設置爲this.toBase64Image()

輸出中看到以下小提琴:

https://jsfiddle.net/wveepa7c/

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

1

onComplete在jsfiddle中至少調用兩次。你可以在onComplete檢查限定,如果變量被定義爲防止<img>被附加到document兩次,如果沒有定義的變量,創建<img>元件,使用.insertAdjacentHTML()ctx與第一參數"afterend"<img>秒參數.outerHTML的變量而言undefined,元件

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/