How to Download a Photo of CanvasJS on Submit

2019-09-05 21:52发布

问题:

I am using Canvas JS to create a graph image inside of my form. Currently, an image can be created of the graph by clicking the 3 dotted button (shown in the image below), and then hitting "Save as PNG".

When someone submits the form, I want an image of the graph to be created, which will then get sent to the person filling the form out.

However, I cannot figure out how to do this. Here is what I have tried using JQuery:

$(document).ready(function() {
    $('.submit-button').click(function(e) {  
        $("button[title='More Options']").first().click();
        $("div").text('Save as PNG').click();
    });
});

(When I click submit, it doesn't download anything. My JQuery is set up, as well [I have tested the function with alerts].)

An example of the graph can be seen here:

http://canvasjs.com/docs/charts/chart-options/export-file-name/

回答1:

The required div is not selected properly. You can use:

$( document ).ready(function (){
  $('.submit-button').click(function () {
    $('.canvasjs-chart-toolbar > div > div')[0].click(); // 0 for JPEG, 1 for PNG
  });
});

Please refer to this working fiddle.

Alternatively, you can use toDataURL to export CanvasJS Chart as image. Please refer to this fiddle.