Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

javascript - Save flot graph as image

Hi I am trying to save flot graph as image (png/jpeg..). I look into other questions they advice to use canvas.toDataURL("image/png"); or canvas2image. However I am using div for flot as follows.

<div id="graph"> <div id="graphc" style="width: 600px;height:153px; top: 560px; left:120px; auto;"> </div> </div>

plot= $.plot($("#graph #graphc"),
           [ {data: data5 ],
           xaxis: { mode: "time",minTickSize: [10, "second"],
            timeformat: "%0H:%0M" } } );

How can I save this graph? Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to get the canvas that flot creates within your div. If you look at the docs you'll see there is a .getCanvas() function. Or you could probably use jQuery to select a canvas inside your div.

Once you have the canvas, you can use .toDataURL or any other technique.

So you have this:

plot= $.plot($("#graph #graphc"),
       [ {data: data5 ],
       xaxis: { mode: "time",minTickSize: [10, "second"],
        timeformat: "%0H:%0M" } } );

And then you should be able to do this:

var myCanvas = plot.getCanvas();

To actually download a file, you would need to use .toDataURL(), then replace image/png mime type with image/octet-stream and then set your document.location.href to your string:

var image = myCanvas.toDataURL();
image = image.replace("image/png","image/octet-stream");
document.location.href=image;

Or you can use canvas2image to do all of this for you.

Edit: The only problem with this is, in FireFox at least, the image will be saved with a random looking name and a .part extension. Changing it to .png will reveal that it is the actual image. Not sure if there's a good way to convince the browser to save it with a friendly name, or at least one with the correct extension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...