Page 1 of 1

Best practices to saving HTML5 Canvas as an image

Posted: Wed Mar 07, 2018 1:03 am
by 9231184
So I'm trying to implement a link/button of sorts such that a client can click the button, (possibly select folder location as well) and download a TeeChart in the highest quality possible. I'm aware right-click on the canvas into Save Image As works as a feature in some browsers, however I'm looking if there is clickable alternative that will be more universal.

I've tried using

Code: Select all

Chart1.toImage('test', 'png')(
which displays the image fine using the <img id = 'test'> tag as shown in the demo example but I'm lost to where to go from here in terms of programatically downloading this image, I don't actually want to display the image just download it.

I've tried some common non-TeeChart methods such as:

Code: Select all

href = "document.getElementById('Canvas1').toDataURL();"
alongside the download attribute to download as Base64 and some other methods, however I'm not very well experienced in this area and was wondering if there was a 'universal' method, TeeChart supported or not. Also some suggestions online are simply outdated. With some research, apparently in Base64 form (as my TeeCharts can start to get quite large) our charts produces too many characters for certain browsers to accept using some methods. Working examples only tests very small files.

Thanks in advance,

Re: Best practices to saving HTML5 Canvas as an image

Posted: Wed Mar 07, 2018 12:10 pm
by yeray
Hello,

The following code seems to work fine for me here:

Code: Select all

<button onclick="getPngChart();">Get Png</button>

Code: Select all

function getPngChart() {
  var element = document.createElement('a');
  element.setAttribute('href', document.getElementById('canvas').toDataURL('image/png'));
  element.setAttribute('download', 'chart.png');
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}
Could you please arrange a simple example where it fails so we can further investigate?

Re: Best practices to saving HTML5 Canvas as an image

Posted: Mon Mar 12, 2018 10:33 pm
by 9231184
There seems to be an issue with the earlier annotations issue. When I have it disabled it will work. Otherwise could you show me how to implement saving a canvas with an annotation attached:

https://jsfiddle.net/norike82/rp83jLgm/

If it is relevant, having the scroller isn't a big concern as of now since it conflicted with annotations

Re: Best practices to saving HTML5 Canvas as an image

Posted: Tue Mar 13, 2018 9:48 am
by yeray
Hello,

Are you getting an error like this?
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
In that case, you have to get your image resource in a cross-origin compliant way.