Open flash chart (hereinafter referred to as OFC) is no longer described in many web blogs; here, we will only record some of the uncommon features of OFC over the past few days, so as not to forget it again and have the right to take study notes.
1. Get OFC chart objects
Since the OFC object embedded on the page is used in many of the following places, a method to obtain the object is defined here:
function findSWF(movieName) { var movies = $("#" + movieName); if(movies && movies.length && movies[0].tagName !== 'DIV') return movies[0]; }
The parameter moviename here is actually the ID specified when the SWF file of the OFC chart is loaded. If it is not specified when the SWF file is embedded, that is, the last parameter of embedswf does not have a similar {ID: the Code of 'custom'} uses the ID of the HTML element by default.
As follows:
Swfobject. embedswf (flashpath, "chart", "100%", "100%", "9.0.0", "expressinstall.swf", {},{ ID: 'custom '}); // The ID is customswfobject. embedswf (flashpath, "chart", "100%", "100%", "9.0.0", "expressinstall.swf", {},{}); // The ID is the chart
2. open_flash_chart_data () method
OFC is embedded on the page. If data-file is not specified when the SWF file is embedded, when the page is accessed and loaded, the JavaScript method is called to search for chart data, therefore, we can define this method on the page and create JSON data (or other paths, such as request data to the server) in the method implementation, then convert the JSON data to a string and return it. When OFC acquires data, it can render the corresponding Chart content.
Example:
function open_flash_chart_data() {$.ajax({url: contextPath + '/ofc2/chart!barChart.action',type: 'post',data: {},dataType: 'json',success: function(data) {findSWF("chart").load(JSON.stringify(data));}});return "";}
The above code is embedded in SWF to obtain data in Ajax mode, and then dynamically update OFC chart data. Because the data is obtained from the server and Ajax is asynchronous, The open_flash_chart_data method cannot directly return a JSON string, but can only return a Null String. The data is transmitted to OFC only after the Ajax request is returned. This is actually not practical, because we can specify the URL when embedding the SWF file and request data by OFC itself, which can save a lot of code, here is just an example to help you understand.
3. ofc_ready () method
This callback function is called after the OFC loads data. In this function, you can perform some operations, such as starting a timer to dynamically obtain the latest data and then loading the latest data in the OFC on the page, this allows you to dynamically update OFC.
Example:
/*** After loading data in OFC, start the timer and update the chart once every two seconds */function ofc_ready () {setinterval (function () {Update ();}, (2000 );}
4. OFC reload data (Chart Update)
Because OFC chart data is held in the form of a JavaScript Object in the browser (or re-load data to the server), it is very easy to operate on it, then, let the chart flash dynamically load data to dynamically update the chart. Here, the Javascript callback interface load exposed by the OFC chart object is used:
/*** Operation data code, modify data or obtain data again based on personal needs. * The data parameter here is a JSON object, JSON. the stringify method is to convert it to a string, and the method is defined in json2.js */findswf ("chart "). load (JSON. stringify (data ));
In this way, when the data is correct, the chart will be re-rendered to complete dynamic updates. Of course, the chart style can be changed at will, not just the Chart Content update. For example, we can change the pie chart to a line chart and then to a column chart, you can also change the column chart data and then re-render it into a column chart, but the height of the column has changed. Therefore, the rendering is entirely dependent on the data.
5. generate images from Charts
On the official website, there are two options for saving charts as images:
1. generate an image and upload it to the server for storage;
Second, generate an image and pass it to the JavaScript function;
5.1 upload to server
OFC exposes an interface to upload image data to the server, which is the post_image () method. The interface is defined as follows:
/*** @ Param URL is a string, that is, the Image Upload path, can be followed by parameters such as http://example.com/ofc/ofc_upload_img.php? Name‑chart.jpg * @ Param callback string type, specifying a JavaScript method name as the callback function after the image is uploaded successfully. Only when the debug parameter is false can the * @ Param debug boolean type be used, if this parameter is set to true, a window is displayed again. */post_image (URL: String, callback: String, debug: Boolean );
For example, we can call:
findSWF("chart").post_image(contextPath + "/ofc2/chart!postPicture.action?name=postImage",'',false);
When we execute this code, OFC will submit the image data to the given URL resource. The struts2 action is used here, however, I still don't know how to receive data from actions, and no examples have been found on the official website.
5.2 hand over to JavaScript for processing
If it is handed over to JavaScript for processing, it will be more operable. We can display the image directly on the current page or in a new window, or upload the image to the server for storage; even the simulated image download method is used by the server to receive image data, convert it into an image, and then write the file stream back to the page. Regardless of the operation, the first thing we need to do is to obtain image data. Here we use another interface exposed by OFC: get_img_binary (), this method is used to obtain the base64 encoding of the image data corresponding to the chart.
For example, we can pass the image data directly to an IMG element and render it to an HTML page (IE7 and IE7 do not seem to support base64-encoded Image Display), for example:
VaR base64data = findswf ("chart "). get_img_binary (); // get the base64 encoding of the image data corresponding to the chart $ ("# showimg "). empty (). append ("
For example, if we submit the obtained base64 encoding to the server, the server decodes the image and then writes it back to the page as a file stream, which is similar to downloading the image:
/*** Put the image base64 encoding into a hidden domain on the page, and submit the form of the hidden domain. * The file storage dialog box appears when the server writes a file stream, this is similar to saving an image... "*/$ (" input [name = 'imgbase64code'] "). val (findswf ("chart "). get_img_binary (); $ ("# savepicform "). submit ();
5.3. The server receives base64 encoded image data
If we submit the base64 encoding of the image to the server, we need to perform base64 Decoding in the background to obtain the original data, then, output the decoded data to the browser to implement or save the image-like download function. The decoding methods may be different for each server language. In Java, you can use the base64decoder class to decode the data.
Example (use struts2 action, refer to the network example ):
Public String savepicture () throws exception {httpservletrequest request = servletactioncontext. getrequest (); httpservletresponse response = servletactioncontext. getresponse (); string imgbase64code = request. getparameter ("imgbase64code"); response. setcontenttype ("image/PNG; charset = UTF-8"); response. setheader ("content-disposition", "attachment; filename =" + new string ("flashexport.png ". getbytes (), "iso-8859-1"); base64decoder decoder = new base64decoder (); byte [] buffer = decoder. decodebuffer (imgbase64code); For (INT I = 0; I <buffer. length; ++ I) {If (buffer [I] <0) {buffer [I] + = 256; // adjust abnormal data} response. getoutputstream (). write (buffer); return NULL ;}
6. save_image_locally
OFC reserves an interface in the right-click menu of FLASH: save_image_locally. When this menu item is clicked, it calls the JavaScript method defined on the page as save_image. Therefore, we can also use this interface as the entry to the Javascript described in the previous step to process the image data generated by the chart. For example, we define the following JavaScript method:
// When you right-click the "save_image_locally" option in the menu, function save_image () {$ ("input [name = 'imgbase64code']") is triggered. val (findswf ("chart "). get_img_binary (); $ ("# savepicform "). submit ();}
7. Complete example
The following is a complete example, which contains all the content described above. The example does not focus on how to generate various charts, the main test is the interaction between OFC and Js.
7.1 ,:
7.2 dependent JS files
<script type="text/javascript" src="<%=path %>/js/jquery-1.7.2.min.js"></script><script type="text/javascript" src="<%=path %>/js/jquery-ui.min.js"></script><script type="text/javascript" src="<%=path %>/js/json2.js"></script><script type="text/javascript" src="<%=path %>/js/ofc2/swfobject.js"></script>
7.3. html structure in JSP pages
<Input type = "hidden" id = "contextpath" value = "<% = request. getcontextpath () %> "/> <div> <button onclick =" chart () "> load chart </button> <button onclick =" outputaspicture () "> output as image </button> <button onclick =" save_image () "> Save As image </button> <button onclick =" saveaspicture () "> Save As image (post_image) </button> <button onclick =" updatechart () "> Update chart </button> <Div id =" content "style =" width: 540px; Height: 360px; Border: 2px solid red; "> <D IV id = "chart"> </div> <Div id = "showimg" style = "width: 540px; Height: 360px; Border: 2px solid red; "> the image is displayed here </div> <form action =" <% = PATH %>/ofc2/chart! Savepicture. Action "id =" savepicform "method =" Post "> <input type =" hidden "name =" imgbase64code "/> </form>
7.4 JavaScript implementation
VaR contextpath; $ (function () {contextpath = $ ("# contextpath "). val (); $ ("# Content "). resizable () ;})/*** load the chart */Function Chart () {var flashpath = contextpath + "/JS/ofc2/open-flash-chart.swf "; vaR datapath = contextpath + "/ofc2/chart! Barchart. action "; swfobject. embedswf (flashpath, "chart", "100%", "100%", "9.0.0", "expressinstall.swf", {"data-file": datapath}, {wmode: "Transparent"});}/*** OFC method for obtaining JSON data * @ returns {string} JSON string */function open_flash_chart_data () {$. ajax ({URL: contextpath + '/ofc2/chart! Barchart. action ', type: 'post', data :{}, datatype: 'json', success: function (data) {findswf ("chart "). load (JSON. stringify (data) ;}}); Return "" ;}/ *** after loading data in OFC, start the timer and update the chart once every 2 seconds */function ofc_ready () {setinterval (function () {updatechart () ;}, 2000) ;}/ *** outputs the chart as an image, in the DIV element of the current page */function outputaspicture () {var base64data = findswf ("chart "). get_img_binary (); $ ("# showimg "). empty (). append (" ");} /*** use the post_image interface exposed by OFC to submit image data to the server */function saveaspicture () {findswf ("chart "). post_image (contextpath + "/ofc2/chart! Postpicture. Action? Name = postimage ", 'postone', false );} /*** response function * @ Param ID */function postdone (ID) {alert ('Post image done! The ID is '+ id);}/*** dynamically update chart */function updatechart () {var OFC = findswf ("chart"); If (OFC) {$. ajax ({URL: contextpath + '/ofc2/chart! Barchart. action ', type: 'post', ype: 'json', success: function (data) {OFC. load (JSON. stringify (data) ;}}) ;}/ *** uses a hidden domain to submit base64 encoded image data to the server, simulating the image SAVE Function */function save_image () {var base64data = findswf ("chart "). get_img_binary (); $ ("input [name = 'imgbase64code']"). val (base64data); $ ("# savepicform "). submit ();}/*** get the OFC object * @ Param moviename the ID specified when loading OFC * @ returns the specified OFC */function findswf (moviename) {VaR Movies = $ ("#" + moviename); If (movies & movies. Length & movies [0]. tagname! = 'Div ') return movies [0];}
7.5 struts2 Action Implementation
The following is the server code, which is implemented using struts2 action and depends on the open-source project jofc2. JSON data and image download functions required to assemble OFC to generate a column chart. Class import is omitted.
Package COM. zyh. action. ofc2; // import code; public class chartaction extends actionsupport {Private Static final long serialversionuid = 1l;/*** generate a column chart, assemble data required by OFC rendering column chart */Public String barchart () {barchart = new barchart (style. glass); barchart. settext ("test here"); random = new random (); xaxis = new xaxis (); xaxis. setcolour ("#909090"); xaxis. setgridcolour ("# adb5c7"); int max = 0; For (INT I = 0; I <10; I ++) {int temp = random. nextint (100); If (max <temp) max = temp; bar = new bar (temp); barchart. addbars (bar); label Label = new label ("test" + temp); xaxis. addlabels (Label);} yaxis = new yaxis (); yaxis. setmax (MAX + 10); yaxis. setsteps (max/10); Chart chart = new chart ("chart test", "{font-size: 20px; font-weight: bold; color: # a2acba; text-align: center;} "); chart. addelements (barchart); text xlegend = new text ("X axis Legend", "{font-size: 16px; font-weight: bold; color: # a2acba; text-align: center;} "); chart. setxlegend (xlegend); text ylegend = new text ("Number", "{font-size: 16px; font-weight: bold; color: # a2acba; text-align: center;} "); chart. setylegend (ylegend); chart. setxaxis (xaxis); chart. setyaxis (yaxis); try {system. out. println (chart. tostring (); writechart (chart, servletactioncontext. getresponse ();} catch (exception e) {e. printstacktrace ();} return NULL;} private void writechart (Chart chart, httpservletresponse response) throws exception {response. setcontenttype ("application/JSON-RPC; charset = UTF-8"); response. setheader ("cache-control", "No-Cache"); response. setheader ("expires", "0"); response. setheader ("Pragma", "No-Cache"); printwriter writer = response. getwriter (); writer. write (chart. tostring (); writer. flush (); writer. close ();}/*** this method is used to respond to the post_imgae () interface exposed by OFC, but does not know how to obtain image data. It is temporarily idle */Public String postpicture () {httpservletrequest request = servletactioncontext. getrequest (); system. out. println (request. getparameter ("name"); return NULL;}/*** receives the base64 encoding of the image, decompress it, and output it to the page to form the download effect */Public String savepicture () throws exception {httpservletrequest request = servletactioncontext. getrequest (); httpservletresponse response = servletactioncontext. getresponse (); string imgbase64code = request. getparameter ("imgbase64code"); response. setcontenttype ("image/PNG; charset = UTF-8"); response. setheader ("content-disposition", "attachment; filename =" + new string ("flashexport.png ". getbytes (), "iso-8859-1"); base64decoder decoder = new base64decoder (); byte [] buffer = decoder. decodebuffer (imgbase64code); For (INT I = 0; I <buffer. length; ++ I) {If (buffer [I] <0) {buffer [I] + = 256; // adjust abnormal data} response. getoutputstream (). write (buffer); return NULL ;}}