我使用PhantomJs(类似于node.js但不同)服务器端运行与客户端完全相同的代码,并获得相同的结果。你只需要一个单独的exe文件(就像一个独立的webkit浏览器)
下面的程序(用Perl编写,但应该可以翻译成您喜欢的语言)获取一些数据,将其插入到web页面中(可能是ajax请求),然后将该网页发送给客户端,或将其存储为临时文件,并在同一页上启动PhantomJs。然后请PhantomJs生成一个jpg,这个jpg随后被选中(并在这种情况下发送给客户端)。
use strict;
use File::Temp;
$|=1;
use CGI;
my $show_as_jpg = CGI::param("jpg");
use FindBin;
my $script_path = $show_as_jpg
? $FindBin::Bin."/Scripts"
: './Scripts';
my $data = [[2,5,4], [6,4,5]];
my $json_data;
eval {require JSON; $json_data=JSON::to_json($data)};
$json_data ||= "[[2,5,4], [6,4,9]]";
my $graph_html =qq|
<!DOCTYPE html>
<html>
<head>
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="$script_path/excanvas.min.js"></script><![endif]-->
<script class="include" type="text/javascript" src="$script_path/jquery.min.js"></script>
<script class="include" type="text/javascript" src="$script_path/jquery.jqplot.min.js"></script>
<script class="code" type="text/javascript" language="javascript">
jQuery(document).ready(function(){
/*data from perl (\$json_data) inserted here */
var data = $json_data;
jQuery.jqplot("chart1", data );
});
</script>
</head>
<body>
<div id="chart1" style="width:600px; height:400px;"></div>
<a href='?jpg=1'>View as jpg</a>
</body>
</html>
|;
my $phantom_doc_js =qq|
var system = require('system');
//read from commandline which files to open, and write to
var open_doc = system.args[1];
var return_doc = system.args[2];
var page = require('webpage').create();
page.open(open_doc, function () {
page.render(return_doc);
phantom.exit();
});
|;
if ($show_as_jpg) {
my ($phantom_doc_filehandler, $phantom_doc_filename) = File::Temp::tempfile( SUFFIX => '.js', TMPDIR => 1);
my ($phantom_graph_filehandler, $phantom_graph_filename) = File::Temp::tempfile(SUFFIX => '.html', TMPDIR => 1);
my (undef, $image_filename) = File::Temp::tempfile( SUFFIX => '.jpg',TMPDIR => 1, OPEN => 0);
print $phantom_doc_filehandler $phantom_doc_js; close $phantom_doc_filehandler;
print $phantom_graph_filehandler $graph_html; close $phantom_graph_filehandler;
system($FindBin::Bin.'\\phantomjs', $phantom_doc_filename, $phantom_graph_filename, $image_filename) == 0
or die "system failed: $?";
my $img = slurp_file($image_filename);
print "Content-Type: image/jpeg\nPragma: no-cache\n\n".$img;
unlink $phantom_doc_filename, $phantom_graph_filename, $image_filename;
} else {
print "Content-Type: text/html\nPragma: no-cache\n\n".$graph_html;
}
sub slurp_file{
my $filename = shift;
my $string;
local $/ = undef;
open FILE, $filename or die "Couldn't open file: $!";
binmode FILE;
$string = <FILE>;
close FILE;
return $string;
}