I
I
Irina Sokolovskaya2016-01-23 11:36:28
JavaScript
Irina Sokolovskaya, 2016-01-23 11:36:28

How to get data via the VKontakte API and display it in canvas?

Good afternoon. I want to get the number of subscribers in each of several groups through the VKontakte API and display them as a bar chart in canvas. The code for what I did is here .
With test data, the chart in the canvas is displayed. If I write getMembers(1) in the console, then the data on the number of subscribers is displayed in the console.
For some reason, the output result of getMembers(1) is not assigned to a variable and is not displayed on the chart. What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivanq, 2016-01-23
@ierhyna

The code
window.onload = function() {
  // init chart
  initChart();
};

// VK app
VK.init({
  apiId: 5225204
});

function getMembers(gid, callback) {
  VK.Api.call('groups.getById', {group_id: gid, fields: 'members_count'}, function(data){
    if(data.response) {
      console.log('success');
      console.log(data.response[0].members_count);
      callback(data.response[0].members_count);
    } else {
      console.log('error');
    }
  });
}

// get groups members
getMembers('group1', function(gr1) {
  getMembers('group2', function(gr2) {
    getMembers('group3', function(gr3) {
      getMembers('group4', function(gr4) {
        // draw chart
        var chartData = [gr1, gr2, gr3, gr4];
      });
    });
  });
});// var chartData = [343, 123, 432, 963]; // test chart
var canvas, ctx;

function initChart() {
  canvas = document.getElementById('chart');
  ctx = canvas.getContext('2d');
  drawChart(80, 370);
}

function drawChart(x, y) {
  ctx.fillStyle='orangered';
  for (var i = 0; i < chartData.length; i++) {
    ctx.fillRect(x + i * 100, y, 60, chartData[i] / -10);
  }
}

Callback is used here - first it is called getMembers, the request to VK begins and undefined is returned . After that, the request is executed and your function is called. Her return goes nowhere. To do this, you must rewrite the function so that it is given a callback in the parameter - a function that is called after execution. In my code, it is called getMembers(1)and stored in gr1, then getMembers(2), etc. Then chartData = [gr1, gr2, gr3, gr4]. After that, write your code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question