Reputation: 524
I'm using charts.js which has an option to add an attribute containing a base64 image of the canvas, like this:
animation: {
onComplete: function(animation){
document.querySelector('#myChart').setAttribute('href', this.toBase64Image());
}
},
Here is the full working fiddle: https://jsfiddle.net/0on3f7t7/
When you inspect the canvas you can see a href attribute containing the image, so that works. But instead I need to display the image below the canvas. So, yes, there will be two charts on the screen, the canvas version and the image version.
I can't find an answer to this question anyway, and the documentation doesn't give any clues.
Upvotes: 0
Views: 3539
Reputation: 111
You need to add an <img>
element to your page, and then set the src
attribute of the <img>
element to the output of this.toBase64Image()
See the following fiddle:
https://jsfiddle.net/wveepa7c/
onComplete: function(animation){
// #myImage is an img element
document.querySelector('#myImage').setAttribute('src', this.toBase64Image());
}
Upvotes: 4
Reputation: 1
onComplete
is called at least two times at jsfiddle. You can define a variable which is undefined
, at onComplete
check if variable is defined to prevent <img>
being appended to document
twice, if variable is not defined, create <img>
element, use .insertAdjacentHTML()
chained to ctx
with first parameter "afterend"
and second parameter .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/
Upvotes: 1