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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...