如何在node.js中加载Google Charts? [英] How do I load Google Charts in node.js?

查看:174
本文介绍了如何在node.js中加载Google Charts?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在node.js中加载Google图表时,没有任何反应。



我尝试加载第一个示例,但在任何情况下都不会加载图表。 / p>

最终目标是检索生成图表的SVG数据以导出为图像或PDF。因此,如果可以使用替代方法(使用node.js或PHP的服务器端)来实现此目的,我可以接受建议。



注意 >:我已经使用gChartPhp成功生成了几张图表的图像,但是这个项目的要求表明,嵌入式版本是当前API提供的交互式版本,并且导出的版本与嵌入式版本在视觉上是相同的,显然)。



编辑:我标记了 PhantomJS ,因为这是我最终去的解决方案。

缺少链接,但垃圾邮件阻止机制只允许我发帖2.

解决方案

这不是理想的解决方案,但我找到了节点的替代方案。 js在 PhantomJS 中完成相同的最终目标。只需创建一个包含图表(test.html)和类似node.js的HTML文件,创建一个包含代码的JS文件(test.js)。然后使用PhantomJS运行JS文件。



在您的JS文件中,将HTML文件作为网页打开,然后进行渲染,将图像缓冲区保存到文件中:

  var page = require('webpage')。create(); 
page.open('test.html',function(){
page.render('test.png');
phantom.exit();
});

然后运行它:

  phantomjs test.js 

要动态创建图表,请创建以下JS file(test2.js):

  var system = require('system'); 
var page = require('webpage')。create();
page.onCallback =函数(数据)
{
page.clipRect = data.clipRect;
page.render('test.png');
phantom.exit();
};
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js',function()
{
page。 includeJs('https://www.google.com/jsapi',function()
{
page.evaluate(函数(chartType,data_json,options_json)
{
var div = $('< div />').attr('id','chart').width(900).height(500).appendTo($('body'));
google .load(visualization,1,
{
packages:[chartType =='GeoChart'?'geochart':'corechart'],
callback:function()
$ b data_arr = $ .parseJSON(data_json);
data = google.visualization.arrayToDataTable(data_arr);
options = $ .parseJSON(options_json);
chart = new google.visualization [chartType]($(div).get(0));
google.visualization.events.addListener(chart,'re ady',function()
{
window.callPhantom(
{
clipRect:$(div).get(0).getBoundingClientRect()
});
});
chart.draw(data,options);
}
});
},system.args [1],system.args [2],system.args [3]);
});
});

然后运行它:

  phantomjs test2.js LineChart'[[Date,Steve,David,Other],[Dec 31,8,5,3],[Jan 1 ,7,10,4],[Jan 2,9,4,3],[Jan 3,7,5,3]]''{hAxis.slantedText:true}'

phantomjs test2.js PieChart'[[Employee,Calls],[Steve,31],[David,24],[其他,13]]''{is3D :true}'

phantomjs test2.js GeoChart'[[State,Calls],[US-CA,7],[US-TX,5], [US-FL,4],[US-NY,8]]''{region:US,resolution:provinces}'

要从外部脚本获取图像数据,请复制test2.js(test3.js)并更改

  page.render('test.png'); 

 的console.log(page.renderBase64( 'PNG')); 

然后调用它(例如从PHP):

 <?php 

$ data = array(
array(Employee,Calls),
数组(Steve,31),
数组(David,24),
数组(Other,13)
);
$ options = array(
is3D=> true
);
$ command =phantomjs test3.js PieChart'。 json_encode($ data)。 ''。 json_encode($ options)。 ;
unset($ output);
$ result = exec($ command,$ output);
$ base64_image = implode(\\\
,$ output);
$ image = base64_decode($ base64_image);

?>

注意:回顾整个过程,我遇到的问题与node.js可能是我没有设置回调或超时等待图表准备好。


When I attempt to load a Google Chart in node.js, nothing happens.

I tried loading the first example from the line chart docs in both zombie.js and jsdom, but the chart never loads in either case.

The end goal is to retrieve the SVG data of the generated chart for export into an image or PDF. So if an alternate method (server side using node.js or PHP) to achieve this is possible, I'm open to suggestions.

NOTE: I have successfully generated a images of a few charts using gChartPhp, but the requirements of this project state that the embedded version be the interactive version provided by the current API and the exported version be visually IDENTICAL to the embedded one (without being interactive, obviously).

Edit: I tagged PhantomJS, since that is the solution with which I ultimately went.

Sorry for the lack of links, but the spam prevention mechanism will only allow me to post 2.

解决方案

It wasn't the ideal solution, but I found an alternative to node.js for accomplishing the same end goal in PhantomJS. Simply create an HTML file containing the chart (test.html) and like node.js, create a JS file containing your code (test.js). Then run your JS file with PhantomJS.

In your JS file, open your HTML file as a webpage, then render it, either saving the image buffer to a file:

var page = require('webpage').create();
page.open('test.html', function () {
    page.render('test.png');
    phantom.exit();
});

Then run it:

phantomjs test.js

To dynamically create a chart, create the following JS file (test2.js):

var system = require('system');
var page = require('webpage').create();
page.onCallback = function(data)
{
    page.clipRect = data.clipRect;
    page.render('test.png');
    phantom.exit();
};
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function()
{
    page.includeJs('https://www.google.com/jsapi', function()
    {
        page.evaluate(function(chartType, data_json, options_json)
        {
            var div = $('<div />').attr('id', 'chart').width(900).height(500).appendTo($('body'));
            google.load("visualization", "1",
            {
                packages:[chartType == 'GeoChart' ? 'geochart' : 'corechart'],
                callback: function()
                {
                    data_arr = $.parseJSON(data_json);
                    data = google.visualization.arrayToDataTable(data_arr);
                    options = $.parseJSON(options_json);
                    chart = new google.visualization[chartType]($(div).get(0));
                    google.visualization.events.addListener(chart, 'ready', function()
                    {
                        window.callPhantom(
                        {
                            clipRect: $(div).get(0).getBoundingClientRect()
                        });
                    });
                    chart.draw(data, options);
                }
            });
        }, system.args[1], system.args[2], system.args[3]);
    });
});

Then run it:

phantomjs test2.js LineChart '[["Date","Steve","David","Other"],["Dec 31",8,5,3],["Jan 1",7,10,4],["Jan 2",9,4,3],["Jan 3",7,5,3]]' '{"hAxis.slantedText":true}'

phantomjs test2.js PieChart '[["Employee","Calls"],["Steve",31],["David",24],["Other",13]]' '{"is3D":true}'

phantomjs test2.js GeoChart '[["State","Calls"],["US-CA",7],["US-TX",5],["US-FL",4],["US-NY",8]]' '{"region":"US","resolution":"provinces"}'

To get the image data from an external script, make a copy of test2.js (test3.js) and change

page.render('test.png');

to

console.log(page.renderBase64('png'));

Then call it (from PHP, for example):

<?php

    $data = array(
        array("Employee", "Calls"),
        array("Steve", 31),
        array("David", 24),
        array("Other", 13)
    );
    $options = array(
        "is3D" => true
    );
    $command = "phantomjs test3.js PieChart '" . json_encode($data) . "' '" . json_encode($options) . "'";
    unset($output);
    $result = exec($command, $output);
    $base64_image = implode("\n", $output);
    $image = base64_decode($base64_image);

?>

NOTE: Looking back on this whole process, the problem I was having with node.js was possibly that I didn't setup callbacks or timeouts to wait until the charts were "ready".

这篇关于如何在node.js中加载Google Charts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆